HTTP-based API design principles
Here are a few simple principles I use when I'm designing an API myself. There's much more guidance online at various levels of complexity, but I think you'll get good results with this simple starter set of principles.
- Use a path prefix like
/api/1.0to future-proof your API. By separating the rest of your website from the API (via/api), it's easier to keep the code and infrastructure separate, which helps with maintaining the code, scaling up to more users, etc. And by including a version (/1.0), you enable yourself to give users backwards compatibility while they transition to your newer versions. - Return results in JSON form.
- Make the first component of an endpoint a noun. So, for example,
instead of
/getmovies, use/movies. - For plural noun endpoints, return a JSON list.
- For singular noun endpoints, return either a string or a dictionary, depending ont the nature of the endpoint.
- Use URL components (the stuff between the slashes of the URL) for the name of the endpoint
and any mandatory parameters. (For example,
/price/<product_id>, where it doesn't make sense to ask for a price unless you know what product you're talking about.) - Use GET parameters (the stuff after the ? in an URL) to filter the results
sent back by the endpoint. (For example,
/books?published_after=1980&genre=scifi.) - [This one is more advanced. Don't worry about it until we discuss it in class in a week or two.] Report errors via HTTP status codes rather than by cooking up your own error format.
- [Also advanced, and not relevant for our work this term.] Use HTTP verbs GET, POST, PUSH, etc. for their original purposes. For example, GET requests should not alter the server's data except for query logs.