I recently had an interview where we went over REST API design. I really never had any experience in designing APIs, but rather using them. After the interviewer and I talked about ways to design an API I decided I wanted to go back and really think about how to make a proper RESTful interface and the following are the notes that might be helpful for others to glance over when they are thinking about making a REST API. This conversation of RESTful will reference Rails at times because that was my experience with REST and lots of behaviors in Rails make sense once you consider how REST works.
Think Nouns
If you think about the API endpoints available when using a scaffold in Rails, the types of names associated with these endpoints tend to be nouns for a reason. Which makes sense and follows the guidelines for REST very well.
Also, think plural nouns.
Bad:
1 2 |
|
Good
1 2 |
|
Use Parameters
Parameters for urls are in the format /noun?name=value&name2=value2
and this should be the way to get more information for a REST command that might not fit within the REST-way of doing things. Think about queries which can filter the type of list being asked when using /noun
or something similar.
The parameters can be used by using the params object in a controller’s method in Rails.
Examples for parameters: filtering the type of response, deciding what type of data to return, pagination
1 2 |
|
Use camel casing for JSON property names.
Errors
Errors should be handled from the server and they should be returned definitely if something goes wrong and possibly if the query didn’t have an issue.
Error messages are usually in JSON format, the following shows some possible formats.
1 2 |
|
1 2 3 4 |
|
1 2 |
|
Response Format
Sometimes the response needed isn’t normal HTML or text, it could be JSON. Remember in Rails a method can respond in multiple formats, one of them could be JSON.
So for a client to request a response to a query in json, the client can either append a parameter, add .json
to the end of the noun, or put application/json
in the accept type in the header.
Non-Nouns
Use verbs for actions such as convert, calculate, etc.
/convert?from=EURO&to=CNY&amount=10
Limited HTTP Methods Alternatives
Put method type as a parameter to query, example:
/dogs?method=post