An effective and productive design of an API requires short term and long term planning. Short term would be the code for immediate requirement and long term would be providing options for extension.
A few tips and tricks will be discussed here to make it easier to build an effective API using least resources and achieving maximum results.
Restful method-Prioritizing noun resources over verb ones.
You could use noun resources instead of verb resources to avoid the result in a huge list of URLs. This would be a burden on the developer and the user to search for a particular file or document. An API needs to be user friendly and provide room for experimenting successfully with the URLs.
The perfect solution for this issue would be using the noun resources.
GET(read) offers two options which are: return list of all files and a specific file.
POST(create) offers two options which is are: add a new file and an error(since there wouldn’t be anything stored in the application without the user adding it).
PUT(Update) offers two options which are: bulk update of all files and update a specific file.
DELETE(delete) offers two options which are: delete all files and delete a specific file.
You could use /files and /file/:id in conjunction with GET, POST, PUT and DELETE to perform operations even if a huge list has been generated.
Transformers for data representation
Transformers, as the name suggests transforms data from one format to another. There are many reasons out of which the most prominent ones would be, control over data you actually output to consumers and prohibit any sensitive information being displayed accidentally.
The benefit of serializing the data as per your requirement and embed related resources within each other is offered by using transformers.
Handling Errors
The easiest way to handle errors would be using HTTP status codes which are pretty much self explanatory.
200 Successful
201 Resource creation successful
204 Successful but no content returned
304 Request not modified
400 Bad request
401 Unauthorized, needs authentication
403 Forbidden
401 Conflict with the current state
Knowing the error code will help pinpoint the issue in the code for resolving it.
Documentation
Documenting your work is a crucial part for an API. Documentation involves a few steps to be followed to make your API productive.
- Resource URL and information
- https://design.api.com/file/:id and requires authentication.
- Parameters
- Specify mandatory and optional ones.
- Example request and result
- Authentication
- Two steps more in authentication. Basic and 0Auth2 which is your username and password and access token to access the API resource respectively.