Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I build a good (web) API

Tags:

api-design

I'm going to build an API for a web app and I'm interested in what people can suggest as good practices.

I'm already planning to make it versioned (version 1 can only control certain aspects of the system, version 2 could control more, but this may need a change in the way authentication is performed that would be incompatible with version 1), and the authentication will be distinct from the standard username/password people use to log in (if someone does use a malicious tool it won't open them up to full impersonation, just whatever the api allows).

Does anyone have further ideas, or examples of sites with particularly good APIs you have used?

like image 510
Cebjyre Avatar asked Aug 29 '08 00:08

Cebjyre


People also ask

What makes a successful API?

A good API must be able to limit the amount of data that can be received in one go, as well as the frequency of requests for data. It should also be able to notify about how many “pages” of the data are left.


2 Answers

Read the RESTful Web Services book, which give you a good overview of how to use REST in practice, and get to up to speed quickly enough to get started now, with some confidence. This is more useful than just looking at an existing API, because it also discusses design choices and trade-offs.

like image 198
Peter Hilton Avatar answered Oct 11 '22 09:10

Peter Hilton


1) Bake the version number directly into the URL rather than passing it as a parameter, since that gives you complete freedom to change the organization of your API namespace with each version bump.

2) Keep your URL rewriting rules (if any) as simple/lean as possible (but no simpler), while making your URLs as beautiful as possible (but no more).

3) Always look for the best HTTP status code you can find for each response (and don't forget about 202 and 207, for example).

4) Implement fascist parameter validation logic, and informative error messages.

5) Use HTTP request headers where appropriate instead of parameters (like Accept, for example, to allow clients to specify the desired data format of the response).

6) Organize your "nouns" in such a way that the URLs used by different client audiences are separated near the "root" of your URL tree (this makes it easier to enforce different authentication mechanisms for those different audiences if needed, or even map different portions of your URL tree to different servers).

7) If you're serving regular web pages off the same domain as your APIs and use the same authentication credentials, require an X-Requested-With header in your API requests so as to avoid XSRF vulnerabiities.

like image 20
Peter Avatar answered Oct 11 '22 08:10

Peter