HTTP: requests, responses and status codes

The language of the web — methods, paths, headers, bodies and status codes — that every API speaks.

Module 3: HTTP and Express · Lesson 7 of 26 · 15 min read · Free

Every interaction with an API is an HTTP request and a response:

An HTTP request and response

The request

  • Method — what you want to do:
    • GET — read (never changes data)
    • POST — create
    • PUT — replace / PATCH — change part of something
    • DELETE — remove
  • Path — what you want it done to: /api/orders/1. Plus an optional query string: /api/menu?category=rice&maxPrice=3000.
  • Headers — extra information: Content-Type: application/json (the body format), Authorization: Bearer … (who you are).
  • Body — the data, for POST, PUT and PATCH — usually JSON.

The response

  • Status code — did it work?
  • Headers — e.g. Content-Type: application/json.
  • Body — the result, or an error message.

Status codes you'll use

HTTP status codes

Choosing the right code matters: apps decide what to show the user based on it.

SituationCode
Read something successfully200 OK
Created something201 Created
Deleted, nothing to return204 No Content
The request is invalid (missing field, bad phone number)400 Bad Request
Not logged in / bad token401 Unauthorized
Logged in but not allowed403 Forbidden
Doesn't exist404 Not Found
Conflicts with existing data (email already registered)409 Conflict
Too many attempts429 Too Many Requests
Your code crashed500 Internal Server Error

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. Which method should be used to create a new order?

    • A POST
    • B GET
    • C DELETE
    • D HEAD
    Show the answer

    A) POST — POST creates; GET only reads.

  2. A user is logged in but tries to delete another user's order. Which status?

    • A 403 Forbidden
    • B 401 Unauthorized
    • C 404 Not Found
    • D 200 OK
    Show the answer

    A) 403 Forbidden — 401 means not authenticated; 403 means authenticated but not allowed.

  3. What does the query string in /api/menu?category=rice do?

    • A Passes optional parameters, such as filters
    • B Sets the request method
    • C Authenticates the user
    • D Nothing
    Show the answer

    A) Passes optional parameters, such as filters — Query parameters customise a GET request.

More free lessons: What the back end does · Install Node.js and use the terminal · Asynchronous code: promises and async/await · Designing a REST API · Designing tables and relationships · Storing passwords safely · Automated tests and project structure