**Comprehensive Notes on APIs for Frontend JavaScript**
---
### **What is an API?**
- **API (Application Programming Interface):** A set of rules that allows one software application to interact with
another.
- **Real-Life Analogy:** Think of an API as a waiter in a restaurant. The waiter takes your order (request), delivers it
to the kitchen (server), and brings back your food (response).
---
### **Types of APIs**
1. **REST (Representational State Transfer):**
- Stateless and lightweight.
- Communicates via HTTP methods like GET, POST, PUT, DELETE.
- Data is usually returned in JSON format.
2. **GraphQL:**
- Flexible and allows clients to specify the data they need.
- Single endpoint for all queries and mutations.
3. **SOAP (Simple Object Access Protocol):**
- Protocol-based and uses XML for communication.
- More complex and less common in modern web development.
4. **WebSocket APIs:**
- Provides real-time, two-way communication between client and server.
---
### **Key HTTP Methods in REST APIs**
1. **GET:** Retrieve data from the server.
- Example: Fetching a list of products.
2. **POST:** Send data to the server to create a new resource.
- Example: Adding a new user.
3. **PUT:** Update an existing resource.
- Example: Editing a user profile.
4. **DELETE:** Remove a resource from the server.
- Example: Deleting a blog post.
---
### **Core Concepts**
1. **Endpoints:**
- The URL where the API can be accessed.
- Example: `https://api.example.com/users`
2. **Request:**
- Sent by the client to the server.
- Includes headers, body, and method (GET, POST, etc.).
3. **Response:**
- Sent by the server to the client.
- Includes status codes, headers, and body (usually JSON).
4. **Status Codes:**
- **200:** Success.
- **201:** Resource created.
- **400:** Bad request.
- **401:** Unauthorized.
- **404:** Resource not found.
- **500:** Server error.
---
### **How to Work with APIs in JavaScript**
1. **Using `fetch()` Method:**
- Syntax:
```javascript
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```
2. **Using Async/Await:**
- Syntax:
```javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
fetchData();
```
3. **Working with Headers:**
- Example:
```javascript
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token_here'
},
body: JSON.stringify({ name: 'Abhignya', age: 22 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```
---
### **Examples and Daily Life Scenarios**
#### **Basic Examples:**
1. **Fetch a Joke:**
```javascript
fetch('https://official-joke-api.appspot.com/random_joke')
.then(response => response.json())
.then(joke => console.log(`${joke.setup} - ${joke.punchline}`));
```
2. **Weather App:**
```javascript
async function getWeather(city) {
const response = await
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=your_api_key`);
const data = await response.json();
console.log(`Temperature in ${city}: ${data.main.temp}`);
}
getWeather('London');
```
3. **Quote of the Day:**
```javascript
fetch('https://api.quotable.io/random')
.then(response => response.json())
.then(quote => console.log(`${quote.content} - ${quote.author}`));
```
#### **Intermediate Examples:**
4. **Search GitHub Users:**
```javascript
async function searchUser(username) {
const response = await fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
console.log(data);
searchUser('octocat');
```
5. **Currency Converter:**
```javascript
async function convertCurrency(amount, from, to) {
const response = await fetch(`https://api.exchangerate-api.com/v4/latest/${from}`);
const data = await response.json();
console.log(`${amount} ${from} = ${amount * data.rates[to]} ${to}`);
convertCurrency(100, 'USD', 'EUR');
```
#### **Advanced Examples:**
6. **Pagination:**
```javascript
async function fetchPaginatedData(page) {
const response = await fetch(`https://api.example.com/data?page=${page}`);
const data = await response.json();
console.log(data);
fetchPaginatedData(1);
```
7. **Chained API Calls:**
```javascript
async function fetchUserAndPosts(userId) {
const userResponse = await fetch(`https://api.example.com/users/${userId}`);
const user = await userResponse.json();
const postsResponse = await fetch(`https://api.example.com/users/${userId}/posts`);
const posts = await postsResponse.json();
console.log(user, posts);
fetchUserAndPosts(1);
```
---
### **50 Practice Questions for APIs**
#### **Basic Questions:**
1. Fetch a list of posts from an API.
2. Display a random image from an API.
3. Fetch and display your public IP address.
4. Create a form to fetch user details from an API.
5. Fetch and display a list of countries.
#### **Intermediate Questions:**
6. Implement search functionality using an API.
7. Add a loader while fetching data.
8. Handle API errors gracefully.
9. Fetch data and sort it alphabetically.
10. Create a dropdown populated with API data.
#### **Advanced Questions:**
11. Use an API to implement infinite scrolling.
12. Implement a login system using token-based authentication.
13. Fetch and display real-time cryptocurrency prices.
14. Create a dashboard with multiple API calls.
15. Integrate WebSockets for real-time chat.
---
### **Small Project Ideas**
1. **Joke App:** Fetch and display random jokes.
2. **Weather Dashboard:** Show current weather for a selected city.
3. **To-Do App with API:** Save tasks using a backend API.
4. **Movie Search App:** Search and display movies using the OMDB API.
5. **E-Commerce Product List:** Fetch and display products from a mock API.
---
This document provides a comprehensive guide to mastering APIs for frontend development. Let me know if you'd
like me to expand on any section or create more detailed examples!