APIs use specific HTTP methods to communicate with the server. These methods define what type of operation you’re trying to perform.
The five most common HTTP methods are:
GET POST PUT PATCH DELETE
Letβs break them down:
GET β Fetch Data From Server
Purpose: Retrieve or read data from a server without modifying it.
π Example Use Case: When a user logs in, the frontend fetches their profile data.
// Example using Fetch API fetch(‘https://api.example.com/user/123’) .then(res => res.json()) .then(data => console.log(data));
Flow Diagram:
Client (Frontend) —> [GET Request] —> Server —> [Response: User Data] —> Client
POST β Send New Data to Server
Purpose: Used to send new data to the server to create a new resource.
π Example Use Case: User signs up β A new user record is created in the database.
fetch(‘https://api.example.com/signup’, { method: ‘POST’, headers: { ‘Content-Type’: ‘application/json’, }, body: JSON.stringify({ name: ‘John Doe’, email: ‘[email protected]’, password: ‘123456’ }), }) .then(res => res.json()) .then(data => console.log(‘User created:’, data));
Flow Diagram:
Client (Signup Form) | |— POST: User Data —> Server (Database) | |— Response: Success Message —> Client
PUT & PATCH β Update Data on Server
Purpose: Both are used for updating existing data on the server.
β PUT:
-
Replaces the entire existing resource.
-
Requires all fields, even if only one changes.
fetch(‘https://api.example.com/user/123’, { method: ‘PUT’, headers: { ‘Content-Type’: ‘application/json’ }, body: JSON.stringify({ name: ‘Updated Name’, email: ‘[email protected]’, password: ‘newpass123’ }) });
PATCH:
-
Updates only specific fields (partial update).
-
More efficient if only one or two fields change.
fetch(‘https://api.example.com/user/123’, { method: ‘PATCH’, headers: { ‘Content-Type’: ‘application/json’ }, body: JSON.stringify({ email: ‘[email protected]’ }) });
Flow Diagram:
Client —> PATCH (only email) —> Server <— Response: Email Updated
DELETE β Remove Data from Server
Purpose: Used to delete a resource from the server.
π Example Use Case: A user deletes their account.
fetch(‘https://api.example.com/user/123’, { method: ‘DELETE’ }) .then(res => console.log(‘User deleted’));