How should I build a good (web) API

前端 未结 5 1838
忘了有多久
忘了有多久 2021-01-30 09:50

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

5条回答
  •  轮回少年
    2021-01-30 10:15

    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.

提交回复
热议问题