This tutorial aims to guide you on how to correctly use HTTP status codes in your responses when building REST APIs. By the end of this tutorial, you will gain a deeper understanding of the common HTTP status codes, their usage, and their importance in the process of creating more robust and meaningful applications.
Prerequisites:
- Basic understanding of REST APIs
- Familiarity with a programming language, preferably JavaScript
- Basic knowledge of HTTP/HTTPS protocols
HTTP status codes are three-digit numbers that are returned by servers to indicate the status of a requested resource. They are grouped into five classes:
Let's dive into the most commonly used status codes in each class:
Let's assume we are using Express.js to create our REST API.
1. Example of 200 OK
app.get('/users', (req, res) => {
const users = getAllUsers(); // Assume this function returns all users
res.status(200).json(users);
});
Here, res.status(200).json(users)
sends a response with status code 200 and JSON data of users.
2. Example of 201 Created
app.post('/users', (req, res) => {
const newUser = createUser(req.body); // Assume this function creates a new user
res.status(201).json(newUser);
});
In this case, res.status(201).json(newUser)
sends a response with status code 201 and JSON data of the newly created user.
In this tutorial, we have covered the importance of using correct status codes in our REST APIs. We have also looked into some common status codes and their meanings. Next, you might want to learn more about the remaining HTTP status codes and when to use them. Here are some additional resources:
Exercise 1: Create an endpoint that returns a 404 Not Found status code when the requested resource is not found.
Exercise 2: Create an endpoint that returns a 401 Unauthorized status code when the user is not authenticated.
Exercise 3: Update the user creation endpoint to return a 400 Bad Request status code when the request body is missing required fields.
Remember, practice makes perfect. Happy coding!