apiThis is a follow up post to “Using HTTP Status Codes correctly in your REST Web API”, and “Using HTTP Verbs correctly in your REST Web API”. Continuing with the theme of RESTful Web APIs, I thought I would touch on the importance of the actual URL/URI part of the Web API. One way we can think of our Web API is as a database exposed through the HTTP layer. Like any good database, we must be careful when designing "the DB model of our Web API". The equivalent to a formal DB Model (ERD for relational databases), is the Resource Modeling that goes into the Web API. Let’s dive right in.

In REST lingo, URI endpoint are referred to as a Resource. From a data standpoint one can think of it as a piece of data describing an entity instance. Here’s some housekeeping rules to keep your Resources neat and clean:

  1. Avoid having your API start at the root domain. The two most common practices are to create a subdomain (such as http://api.mydomain.com), or to have a dedicated base URL different from the root domain (like http://mydomain.com/api). In doing so you ensure the longevity of the URIs assigned to your resource endpoints, and avoid potential collisions with Page URLs you may want to name in certain ways for the website hosted on your root domain. It also helps later on when versioning becomes an issue for a matured Web API.
  2. The resource endpoints should be plural and NOT singular, for example:
    • http://.../api/customers
    • http://.../api/orders
    • http://.../api/products
  3. Use identifiers to locate single elements in the resource URI. An identifier should ALWAYS resolve to the same single resource.
    • http://.../api/customers/123
    • http://.../api/orders/abc77uk
    • http://.../api/books/world-war-z
  4. When designing your resources, the golden rule is “Nouns are GOOD, Verbs are BAD”. Do not use verbs in ANY part of a resource URI.
    • If you see a verb as in a URI, like http://.../api/getcustomers or http://.../api/payfororder, a part of you should die.
    • Do everything in your power to change it, and educate the creators why using verbs is a bad practice.
  5. For non-resource URIs (yes, they do exist) make sure they are CLEARLY functional endpoints.
    • A simple way to do this is to have a special URL path for all functions such as:
      • http://.../api/func/calculate-fees?size=5&weight=8
    • Please don't use non-resource URLs as an excuse to build a RPC style API.
    • Other samples of functional endpoints could be:
      • http://.../api/func/calculateTax?state=fl&amount=10
      • http://.../api/func/randomNumber
      • http://.../api/func/getHash?input=ubniq2

 

As I'm writing this post I cannot think of anything else to add, but this is a good place to start when it comes to the design of your Resource Model for your REST Web API.

Happy coding!

1 Comment