Best practice when you write an API

Some of the points to consider while writing an API:

  • Should be Simple.
  • Should be Intuitive.
    Example: /users/{id}/card-number instead of /users/{id}/pin

  • Should always be consistent.

  • Should avoid camel cases. The normal is to use lower case letters.
    Example: /users/{id}/pending-orders instead of /users/{id}/Pending_Orders

  • Should use dashes instead of underscores.

  • While naming an API, consider it to be a folder. Follow the naming pattern similar to the folder structure.

  • Use Hierarchy.

  • The most important point to keep in mind while designing an API is maintaining the version number in the API.

  • No trailing forward slash.
    Example: /users/{id}/pending-orders instead of /users/{id}/pending-orders/ and both should give the same output.

Naming

Resource should be nouns not verbs

Example: /users/{id} instead of /getUser

GET /tickets Retrieves a list of tickets.
GET /tickets/12 Retrieves a specific ticket.
POST /tickets Create a new ticket.
PUT /tickets/12 Update ticket #12.
PATCH /tickets/12 Partially update ticket#12.
DELETE /tickets/12 Delete ticket#12.

Relationships

If there is a relationship between resources it can be represented like the following example.

Suppose that each tickets has a messages so the end-points will be in the following form.

GET /tickets/12/messages // Retreives all messages related to ticket#12
GET /tickets/12/messages/5 // Retreives message#5 related to ticket#12
POST /tickets/12/messages // Create a new message related in ticket#12
PUT /tickets/12/messages/5 // update message #5 related in ticket#12
PATCH /tickets/12/messages/5 // Partially updates message #5 related in ticket#12
DELETE /tickets/12/messages/5 //Delete message #5 related in ticket#12

Always use SSL

To secure your end-points. SSL helps to protect sensitive information such as logins, passwords, account details and cardholders information for e-commerce websites during Internet communication. All data over network will be encrypted.

Always version your api

Because end-points may be needed to changes or updated so you need to design your end-points with a version that appeared in URL.

Result filtering,sorting and searching

It’s best to keep the base resource URLs as lean as possible. Complex result filters, sorting requirements, and advanced searching

Filtering

Use a unique query parameter for each field that implements filter
EX if i want to get tickets which only opened
/tickets?state=open so state is a query parameter that implements a filter.

Sorting

like filtering a generic parameter sort can be used to describe sorting rules.

  • GET /tickets?sort=-priority - Retrieves a list of tickets in descending order of priority.
  • GET /tickets?sort=-priority,created_at - Retrieves a list of tickets in descending order of priority. Within a specific priority, older tickets are ordered first.

Searching

Sometimes basic filters aren’t enough and you need the power of full text search.
This is a combining between filters and sorting.

  • GET /tickets?sort=-updated_at - Retrieve recently updated tickets
  • GET /tickets?state=closed&sort=-updated_at - Retrieve recently closed tickets.
  • GET /tickets?q=return&state=open&sort=-priority,created_at - Retrieve the highest priority open tickets mentioning the word ‘return’

Aliases for common queries

To make the API experience more pleasant for the average consumer, consider packaging up sets of conditions into easily accessible RESTful paths. For example, the recently closed tickets query above could be packaged up as
GET /tickets/recently_closed .

Prevent abuse

To prevent abuse you can limit API calls using
X-Rate-limit with status code response
429 Too Many Requests

  • X-Rate-Limit-Limit - The number of allowed requests in the current period
  • X-Rate-Limit-Remaining - The number of remaining requests in the current period
  • X-Rate-Limit-Reset - The number of seconds left in the current period.

Caching

HTTP provides a built-in caching framework! All you have to do is include some additional outbound response headers and do a little validation when you receive some inbound request headers.
There are 2 approaches: ETag and Last-Modified

Errors

Just like an HTML error page shows a useful error message to a visitor, an API should provide a useful error message in a known consumable format

API errors typically break down into 2 types: 400 series status codes for client issues & 500 series status codes for server issues.

JSON error body should provide a few things for the developer - a useful error message, a unique error code (that can be looked up for more details in the docs) and possibly a detailed description

Example:

{
  "code" : 1024,
  "message" : "Validation Failed",
  "errors" : [
    {
      "code" : 5432,
      "field" : "first_name",
      "message" : "First name cannot have fancy characters"
    },
    {
       "code" : 5622,
       "field" : "password",
       "message" : "Password cannot be blank"
    }
  ]
}

HTTP Status code

  • 200 OK - Response to a successful GET, PUT, PATCH or DELETE. Can also be used for a POST that doesn’t result in a creation.
  • 201 Created - Response to a POST that results in a creation. Should be combined with a Location header pointing to the location of the new resource
  • 204 No Content - Response to a successful request that won’t be returning a body (like a DELETE request)
  • 304 Not Modified - Used when HTTP caching headers are in play
  • 400 Bad Request - The request is malformed, such as if the body does not parse
  • 401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser
  • 403 Forbidden - When authentication succeeded but authenticated user doesn’t have access to the resource
  • 404 Not Found - When a non-existent resource is requested
  • 405 Method Not Allowed - When an HTTP method is being requested that isn’t allowed for the authenticated user
  • 410 Gone - Indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions
  • 415 Unsupported Media Type - If incorrect content type was provided as part of the request
  • 422 Unprocessable Entity - Used for validation errors
  • 429 Too Many Requests - When a request is rejected due to rate limiting

Subscribe to our Newsletter

Subscribe to tech-hour website to get all updates, new articles, new courses and projects. No spam ever. Unsubscribe at any time.