How to Pass Data to an API or Server
5.0|1 ratingLog in to rate
A practical guide to passing inputs to a server using Query Parameters, Path Parameters, Headers, and Request Bodies.
#http#web-development#backend#api-design
The Four Input Channels
Client-server communications require transmitting parameters. Web developers utilize four principal methods:
- Path Parameters: Used to identify specific resources in the routing hierarchy. Example: /notes/:id.
- Query Parameters: Used for sorting, filtering, or paginating collections. Example: ?sort=asc&limit=10.
- Request Body: Used to send complex payloads, such as JSON forms or image uploads.
- Headers: Used for metadata, authentication tokens, and content negotiations.
Query Parameters Example
javascript
1
2
3
4
5
6
7
8
9
10
11
// Frontend Request
fetch('/api/notes?topic=backend-engineering&limit=5')
.then(res => res.json())
.then(data => console.log(data));
// Backend Express Router Handler
app.get('/api/notes', (req, res) => {
const { topic, limit } = req.query;
console.log(`Fetching ${limit} notes in topic: ${topic}`);
// ...
});Choosing the Right Channel
Follow these rules of thumb:
- If you need to retrieve a unique article, use Path parameters (e.g. API Design).
- If you are searching or sort, use Query parameters.
- If you are submitting large datasets, use the Request Body.
- For auth credentials, always use the
Authorizationheader.
Passing Headers Example
Example
When initiating API requests, specify your headers:
fetch('/api/notes', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer JWT_SECRET_TOKEN' }, body: JSON.stringify({ title: 'New Lesson' }) });
Discussion
Loading discussion...