POST /api/v1/departments
Basic rules:
- You must use HTTP POST method for creating a resource.
- End point must be plural (if not exceptional scenario)
- Proper http response codes must be returned
- Do not add parameters to api, instead use body
Http response codes to return
HTTP Code | When to return |
---|---|
201 - Created | When api creates expected resource successfully |
200 - OK | Sometimes 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 request | When 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 - Conflict | When 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 Code | When to return |
---|---|
207 - Multi Status | When 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 - Accepted | ASYNC? 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