RESTful APIs / HTTP Methods and Status Codes

Using Correct Status Codes in Responses

In this tutorial, you will learn about the common HTTP status codes and how to correctly use them in your responses when developing REST APIs.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers the use of HTTP methods and appropriate status codes in REST APIs.

Introduction

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

Step-by-Step Guide

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:

  1. Informational responses (100–199)
  2. Successful responses (200–299)
  3. Redirection messages (300–399)
  4. Client error responses (400–499)
  5. Server error responses (500–599)

Let's dive into the most commonly used status codes in each class:

  • 200 OK: This is the most common code, indicating a successful GET, PUT, PATCH, or DELETE request.
  • 201 Created: This indicates that a resource was successfully created in response to a POST request.
  • 400 Bad Request: The request was malformed. This could be caused by various actions by the user such as providing invalid JSON data in the request body.
  • 401 Unauthorized: The user is not authorized to access the resource. This is often used when authentication is required and has failed or has not yet been provided.
  • 404 Not Found: The requested resource could not be found.
  • 500 Internal Server Error: This indicates an unexpected server issue.

Code Examples

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.

Summary

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:

Practice Exercises

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help