Master the Basics of APIs
1. HTTP Protocol
- HTTP Methods: HTTP defines a set of request methods for interacting with resources. The most commonly used methods are:
- GET: Retrieve data from a server (read).
- POST: Send data to the server to create a new resource (create).
- PUT: Update an existing resource (update).
- DELETE: Remove a resource (delete).
- HTTP Headers: Headers provide additional information about the request or response, such as content type (
Content-Type: application/json
) or authentication information. - Status Codes: HTTP responses come with status codes to indicate the outcome of the request:
- 200: OK (success).
- 201: Created (resource successfully created).
- 400: Bad Request (client-side error).
- 404: Not Found (resource not found).
- 500: Internal Server Error (server-side issue).
Example:
const express = require('express');
const app = express();
app.use(express.json());
let users = [];
// GET request to fetch users
app.get(‘/users’, (req, res) => {
res.status(200).json(users); // 200 OK
});
// POST request to create a new user
app.post(‘/users’, (req, res) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser); // 201 Created
});
// Error handling for unknown routes
app.use((req, res) => {
res.status(404).json({ message: “Resource not found” }); // 404 Not Found
});
app.listen(3000, () => console.log(‘Server running on port 3000’));
2. RESTful Principles
REST (Representational State Transfer) is an architectural style used to design web services. It relies on:
- Statelessness: Each request from the client to the server must contain all necessary information, as the server does not store client context.
- URIs (Uniform Resource Identifiers): Resources are accessed through URIs like
/users
,/products
. - HATEOAS (Hypermedia As The Engine Of Application State): A RESTful system provides hypermedia links to let clients discover actions dynamically.
Example:
// Express routes implementing RESTful structure
app.get('/users', (req, res) => { /* Get all users */ });
app.post('/users', (req, res) => { /* Create a new user */ });
app.put('/users/:id', (req, res) => { /* Update user by ID */ });
app.delete('/users/:id', (req, res) => { /* Delete user by ID */ });
In REST, you map HTTP methods to CRUD operations:
GET /users
-> Fetch all users.POST /users
-> Create a new user.PUT /users/:id
-> Update a user by ID.DELETE /users/:id
-> Delete a user by ID.
3. JSON/XML
- JSON (JavaScript Object Notation) is the most commonly used data format for APIs today due to its simplicity and ease of use. It’s used to represent structured data.
- XML (eXtensible Markup Language) is another format, though less commonly used today, mostly in legacy systems.
Example (Handling JSON in Express):
// Middleware to parse incoming JSON requests
app.use(express.json());
app.post(‘/data’, (req, res) => {const jsonData = req.body;
res.status(200).json({
message: “Received data”,
data: jsonData
});
});
This example receives JSON data from the client and returns it in the response.
4. CRUD Operations
CRUD refers to the four basic operations that can be performed on data:
- Create: Add new records (e.g., POST).
- Read: Retrieve data (e.g., GET).
- Update: Modify existing data (e.g., PUT or PATCH).
- Delete: Remove records (e.g., DELETE).
Complete Example (CRUD Operations using Node.js and Express):
const express = require('express');
const app = express();
app.use(express.json());
let users = [
{ id: 1, name: ‘John Doe’, age: 25 },
{ id: 2, name: ‘Jane Doe’, age: 28 }
];
// CREATE: Add a new user (POST)
app.post(‘/users’, (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
age: req.body.age
};
users.push(newUser);
res.status(201).json(newUser); // 201 Created
});
// READ: Get all users (GET)
app.get(‘/users’, (req, res) => {
res.status(200).json(users); // 200 OK
});
// UPDATE: Update an existing user (PUT)
app.put(‘/users/:id’, (req, res) => {
const userId = parseInt(req.params.id);
const user = users.find(u => u.id === userId);
if (!user) {
return res.status(404).json({ message: ‘User not found’ }); // 404 Not Found
}
user.name = req.body.name;
user.age = req.body.age;
res.status(200).json(user); // 200 OK
});
// DELETE: Remove a user (DELETE)
app.delete(‘/users/:id’, (req, res) => {
const userId = parseInt(req.params.id);
const userIndex = users.findIndex(u => u.id === userId);
if (userIndex === –1) {
return res.status(404).json({ message: ‘User not found’ }); // 404 Not Found
}
users.splice(userIndex, 1);
res.status(204).end(); // 204 No Content
});
app.listen(3000, () => console.log(‘Server running on port 3000’));
Key Highlights in Example:
- POST (
/users
): Adds a new user and responds with the created user and status code201 Created
. - GET (
/users
): Retrieves all users and returns them with status code200 OK
. - PUT (
/users/:id
): Updates a user by ID. If the user does not exist, it returns404 Not Found
. - DELETE (
/users/:id
): Deletes a user by ID and returns status code204 No Content
upon successful deletion.
Conclusion
This covers the essentials of:
- HTTP Protocol: Understanding methods, headers, and status codes.
- RESTful Principles: Designing stateless APIs with a proper URI structure.
- JSON/XML: Handling data exchange formats.
CRUD Operations: Implementing basic database actions via HTTP methods in Express.