Wednesday, May 1, 2019

How do I write API to create a resource ?

Creating a resource in terms of API is nothing but adding a new resource to some collection (should I say PUSHing a resource?). This means your end point should be plural as it has to indicate a collection.

POST /api/v1/departments

Basic rules:

  1. You must use HTTP POST method for creating a resource.
  2. End point must be plural (if not exceptional scenario)
  3. Proper http response codes must be returned
  4. Do not add parameters to api, instead use body

Http response codes to return

HTTP CodeWhen to return
201 - CreatedWhen api creates expected resource successfully
200 - OKSometimes you do not actually add resource but shift your resource to next step i.e. you add it to another collection so here in background only status gets changed. In such cases you may use this response code. This case is rare.
400 - Bad requestWhen api fails to create resource because request sent by client in either invalid or incomplete. E.g. You want to create department and request does not have department name which leads to mandatory validation error for department name.
409 - ConflictWhen api fails to create resource because it already exists (a conflicting situation). Some people may prefer to use bad request in this case which is not harmful too

Bulk Creation

Rarely you may want to add resources in bulk or batch to avoid round trips. In this case, you need to deal with few more http response codes -
HTTP CodeWhen to return
207 - Multi StatusWhen api tries to create multiple resources then t may happen that few resources succeed and few fail. In such cases, api can return detailed status for each resource. These detailed status can be Created, Conflit, Bad Request (any one from above table)
202 - AcceptedASYNC? if you do not want client to wait for your response and start creation process in background then its good to return Accepted so that client gets feedback to not to wait further.
Its good practice to validate request so that you can ensure successful creation of resources

No comments:

Post a Comment