Node.js course · Part 3: Building an API · lab 3 of 9
Building an API: requests, routes and answers
What a request is actually made of, routing by method and path, reading and checking JSON that came from a stranger, and failing in a way that helps you and tells them nothing.
By the end you can
- Name the parts of a request and pick the right status code for an answer
- Route a request by its method and its path
- Read JSON from outside and reject it when it is wrong
- Separate failures you expected from failures you did not, and answer both safely
Easier if you did first
step 1 of 4
What a request is made of
An API is a counter. Somebody walks up, says what they want, and you hand something back. A request is the thing they said; a response is what you hand over.
A request has four parts. The method is the verb: GET to fetch, POST to create, PUT or PATCH to change, DELETE to remove. The path says which thing: /api/plans/starter. The headers are the small print: what format they can read, who they are. The body is the data they are sending, and only methods that send data have one.
A response has three parts. A status code, which is a number saying how it went. Headers. And usually a body, normally JSON.
The status code is not decoration. It is the part machines read. 200 means fine. 201 means you created something. 400 means their request was malformed. 401 means they are not signed in. 403 means they are signed in and still not allowed. 404 means there is no such thing. 422 means the request was readable but the values were wrong. 429 means they are asking too often. 500 means you broke, not them.
The whole 4xx and 5xx split is worth remembering: 4 means their fault, 5 means yours. Returning 200 with a body saying it failed is the most common mistake in this area, and it quietly breaks everything that trusts the number.
Five questions.
What these words mean
- method
- The verb of a request: GET, POST, PUT, PATCH, DELETE.
- path
- Which thing the request is about: /api/plans/starter.
- header
- A small labelled fact about the request or response.
- body
- The data being sent or returned, usually JSON.
- status code
- A number saying how it went. 2xx fine, 4xx their fault, 5xx yours.
- endpoint
- One method plus one path that you have agreed to answer.
- idempotent
- Doing it twice has the same effect as doing it once.
question 1 of 5
Someone submits your quote form. Which method should the request use?
question 2 of 5
The quote saved successfully. Which status code?
question 3 of 5
The JSON parsed fine, but the email has no @ in it. What do you send back?
question 4 of 5
A signed-in customer asks for someone else's invoice. 401 or 403?
question 5 of 5
Your database connection drops mid-request. What goes back?