Card 02/ 09

ConceptDifficulty: Beginner2 min

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.

The four success codes an API uses, with a scenario, what the response carries, and the client's next step
CodeScenarioResponse carriesClient's next step
200 OKGET /orders/42 returns the orderThe result in the bodyRead the body
201 CreatedPOST /orders creates order 43A Location header naming /orders/43, and usually the new orderStore the new resource's URL
202 AcceptedPOST /exports starts a report that takes minutesWhere to check progress, such as /exports/9Check the status later
204 No ContentDELETE /orders/42/items/7 removes an itemNo bodyNothing 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.