An API (Application Programming Interface) allows one application to interact with another. It’s like a waiter taking your order and bringing back food from the kitchen. For example, when you check the weather on a mobile app, it’s likely using an API to fetch weather data.
Video Explanation:
Resource: What is an API?
Web APIs: Accessed over the internet using HTTP, they follow a client-server model where requests are sent by the client, and responses are returned by the server.
REST APIs: A subtype of Web APIs that follow RESTful principles. REST (Representational State Transfer) uses HTTP requests for communication and is stateless, meaning each request from a client contains all the information the server needs to fulfill that request. This makes them highly scalable and easier to integrate with web services.
Key Characteristics of REST APIs:
Others:
Video Explanation:
Resource: Types of APIs
APIs are integral in many services:
Video Explanation:
HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. It defines how messages are formatted and transmitted, and how web servers and browsers should respond to various commands. HTTP operates as a request-response protocol between a client and server.
HTTPS (Hypertext Transfer Protocol Secure) is the secure version of HTTP. It uses SSL/TLS encryption to secure the data transmitted between the client and server, ensuring that sensitive information like passwords and credit card details remain private.
Key Differences between HTTP and HTTPS:
Request Body: The request body contains data sent by the client to the server. This is typically used in methods like POST, PUT, and PATCH. The body can include different formats, such as JSON, XML, or form data.
Example of a Request Body (JSON):
{
"title": "foo",
"body": "bar",
"userId": 1
}
Response Body: The response body contains data sent by the server back to the client. This can be in various formats, including HTML, JSON, or XML.
Example of a Response Body (JSON):
{
"id": 1,
"title": "foo",
"body": "bar",
"userId": 1
}
HTTP status codes indicate the result of the request. Here are some common status codes and their meanings:
Resource: HTTP Status Codes - MDN Web Docs
Endpoints and URLs:
An endpoint is a specific address where you send requests, usually a URL combined with an HTTP method. For example, https://jsonplaceholder.typicode.com/posts
might be an endpoint to get posts data.
HTTP Methods:
Headers: Headers pass additional information with the request or response. Common headers include:
Query Parameters: Used to sort, filter, and paginate resources.
https://jsonplaceholder.typicode.com/posts?userId=1
Request Body: Data sent to the server when creating or updating resources, usually in JSON format.
{
"title": "foo",
"body": "bar",
"userId": 1
}
Response Codes: Standard HTTP status codes to indicate the success or failure of a request.
200 OK
, 201 Created
, 400 Bad Request
, 404 Not Found
, 500 Internal Server Error
.Example of a REST API Request:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Resource: HTTP Methods and Headers
Proper error handling in fetch requests is crucial to deal with network issues or problems with the request. The Fetch API treats even 404 or 500 HTTP status codes as a successful request, so it’s important to explicitly check the response status:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Resource: Error Handling with Fetch
Sometimes, you need to send additional information with your requests, like API keys or content types. This is done using headers:
fetch('https://jsonplaceholder.typicode.com/posts', {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Resource: Fetch API Headers - MDN Web Docs
JSON (JavaScript Object Notation) is a lightweight data
interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is text-based and follows a syntax inspired by JavaScript object notation, which makes it familiar to JavaScript developers.
JSON data is represented in key-value pairs. Here’s a basic example:
{
"name": "John",
"age": 30,
"isStudent": false,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
Resource: JSON - MDN Web Docs
To convert a JSON string into a JavaScript object, use JSON.parse()
:
const jsonResponse = '{"name": "John", "age": 30}';
const user = JSON.parse(jsonResponse);
console.log(user.name); // Output: John
Resource: JSON.parse() - MDN Web Docs
To convert a JavaScript object into a JSON string, use JSON.stringify()
:
const userObject = { name: "John", age: 30 };
const jsonString = JSON.stringify(userObject);
console.log(jsonString); // Output: '{"name":"John","age":30}'
Resource: JSON.stringify() - MDN Web Docs
Callbacks:
function getUser(userId, callback) {
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json())
.then(user => callback(user))
.catch(error => console.error('Error:', error));
}
getUser(1, user => {
console.log('User fetched:', user);
});
Promises:
function getUser(userId) {
return fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(response => response.json())
.then(user => {
console.log('User fetched:', user);
return user;
})
.catch(error => console.error('Error:', error));
}
getUser(1);
Async/Await:
async function getUser(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const user = await response.json();
console.log('User fetched:', user);
} catch (error) {
console.error('Error:', error);
}
}
getUser(1);
Resource: Async/Await - MDN Web Docs
async function safeGetUser(userId) {
try {
const user = await getUser(userId);
return user;
} catch (error) {
console.error('Failed to fetch user:', error);
return { name: 'Default User', age: 0 };
}
}
Resource: Error Handling in Async Functions
APIs are the glue that connects different software applications, enabling you to leverage external data and functionality in your projects. They open up a world of possibilities in web development. Understanding HTTP and HTTPS, handling requests and responses, and managing errors effectively are crucial skills for any web developer.