Building GET Endpoints for API
Swipe to show menu
GET endpoints are used to retrieve data from the server.
They return data without changing anything.
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Anna' }
];
app.get('/users', (req, res) => {
res.json(users);
});
This endpoint returns all users.
You can also return a single item using a route parameter:
app.get('/users/:id', (req, res) => {
const id = Number(req.params.id);
const user = users.find(u => u.id === id);
res.json(user);
});
Examples:
'/users': returns all users;'/users/1': returns user with id 1.
GET endpoints are the most common way to read data in an API.
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 12
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 1. Chapter 12