Card 02/ 09
Success Codes: 200, 201, 202 and 204
Each success code tells the client something different about what the server did with the request.
The 2xx class says the request worked, and the specific code says how: 200 OK returns a result, 201 Created says a new resource now exists, 202 Accepted says the work has been queued and is not done yet, and 204 No Content says it worked and there is nothing to send back. Choosing the precise code saves the client a guess about what to read next.
| Code | Scenario | Response carries | Client's next step |
|---|---|---|---|
| 200 OK | GET /orders/42 returns the order | The result in the body | Read the body |
| 201 Created | POST /orders creates order 43 | A Location header naming /orders/43, and usually the new order | Store the new resource's URL |
| 202 Accepted | POST /exports starts a report that takes minutes | Where to check progress, such as /exports/9 | Check the status later |
| 204 No Content | DELETE /orders/42/items/7 removes an item | No body | Nothing to read; the action is done |
200 OK is the general success. It suits reads, and writes that return the updated resource. It promises a body, even if the body is an empty list.
201 Created answers a request that made something new, usually a POST to a collection or a PUT to a URL that was empty. Its Location header gives the new resource's URL, so the client does not have to build it from an id.
202 Accepted means the server has taken the request but has not finished it, and may yet fail. It suits slow work such as exports, video processing or bulk imports. The response should say where to check progress, because otherwise the client cannot tell whether the job ever completed. Asynchronous APIs have their own topic later in this subject.
204 No Content means success with an empty body. It suits DELETE, and updates where the client already holds the new state. A client must not try to parse a body from a 204.
What the client should do next. Read the code before the body. A client that only checks "2xx" will treat a 202 as finished work and report success for an export that has not run yet.
So pick the success code that describes what actually happened: returned, created, accepted for later, or done with nothing to say.
← → move through sections and cards