Web API Design Principles Or Web API Design Guidelines

Overview

In this article, I'll explain the best possible ways to implement the web API, design a great web API, and finally, the things to remember while implementing API.

How do you design or build great Web API Applications?

We’re building applications (web, windows, etc...) for end users who are not programmers, who can easily use your application. Here, they are just end users for our application but API is designed only for programmers who can consume our great API and perform whatever operations they want for their applications based on the requirement.

So API developers should be able to think and focus on the below points.

API implementation point of view

  • What does this service need to do?
  • What does this service need to provide?
  • How my API will act as more generic (input, output, and extensible)?

API consumer point of view

  • How can consumers assuredly integrate with our API?
  • How nimbly, they can provide input to us and output for their use from our API?
  • How can consumers spend the bare minimum of effort to get what they need out of this API?

There are some guidelines for designing a great Web API

  1. Documentation
  2. Naming Conventions for Controllers and Actions
  3. Don’t change the state of HTTP Methods
  4. Stability and Consistency
  5. Flexibility
  6. Security
  7. Validation
  8. HTTP Status Codes
  9. Web API Helper page
  10. Logging

1. Documentation

Documentation is essential for Web APIs because, in this, each method describes two things i.e., what it’ll accept and what it’ll provide.

As a developer, I worked on consuming several external web APIs like MailChimp, klaviyo, Salesforce, Bronto, etc. These all are email service providers.

I am required to get a list of emails from each web API. I have many APIs to go through and it needs to integrate each of them. If each API will take only a minimum amount of time to understand what the API is doing and how I can get the result then it’s a great API because of well-marked documentation.

A few APIs are hell I need to spend more time on it because of poor documentation.

Here I am thinking like an API user. So every Web API developer should think from the user's perspective too. Although you are building great APIs for end users, if they are facing a lot of difficulties or spending more time to integrate/understand it, then it’s not a great API.

2. Naming Conventions for Controllers and Actions

  • Use plural nouns for Controllers: Don’t mix up singular and plural nouns. Keep it simple and use only plural nouns for all resources.
    Example
    /products instead of /product
    /users instead of /user
  • Use nouns but no verbs for Actions: Don’t use fully described names for actions. It’s a bad practice.
      GET POST PUT DELETE
    RESOURCE Read Create Update Delete
    /Products Returns a list of products Create a new product Bulk update of products Delete all products
    /Products/101 Returns a specific product Method not allowed (405) Updates a specific product Deletes a specific product
  • Don’t use verbs
    /getAllProducts
    /createNewProduct
    /deleteAllProducts

3. Don’t change the state of HTTP methods

  • HTTP methods have their state of behavior. Don’t change or mix their state.
      GET POST PUT DELETE
    RESOURCE Read Create Update Delete
  • Don’t use verbs
    /metal products
    /createNewProduct
    /deleteAllProducts
  • Example of violated HTTP method rules
    Get Method is used to read the data. Don’t use it to alter the state.
    Delete is only used to delete or inactivate the record.

4. Stability and Consistency

Let’s say, Your API is more successful and it has a lot of clients. Now, you have a requirement to rename one of the fields or add a new field for JSON response. What happens if you modify the changes and publish a web API? Everyone that’s already integrated with you is going to break.

In the software world, we can't blame changes or new feature requests. They are part of the software development. We can't stop them or refuse them either.

The most common way of handling changes is, to have versions of an API.

Versioning

Changes that don’t break existing code using the API can be handled within one version.
If there are breaking changes i.e. it risks breaking the code that is using the API, those changes should be introduced in a new version of the API.

Every developer should do some planning ahead of their web API. Make the API Version mandatory and never release an unversioned API.

Sample of URL version schema

/api/v1/products
/api/products?version=v1
/api/products?api-version=1

/api/v2-Alpha/products
/api/products?api-version=2-Alpha

/api/v2015-05-01.3.0/products
/api/products?api-version=2015-05-01.3.0

5. Flexibility

Flexibility is most important for Web API’s. Let’s say, that if you have a lot of users for your web API, users may need output in JSON format or XML format as per their business needs. So, you can’t say that my API will always return output as JSON. If you say that, you’ll lose your business.

How will you manage that?
How should your API act flexibly (about input, and output)?

Here is the answer you can handle it through URL resources. Please look at the below samples.

5.1). Flexibility on input

By default, Web API will support multiple formats of input types. Those are text/html, JSON, XML, etc.

5.2). Flexibility on output

The below formats give flexibility to end users to choose their output format.

Example Resources

/api/v1/products.Json

/api/v1/products.XML

/api/v1/products/?format=Json

/api/v1/products?format=XML

5.3). Flexibility in filtering

Use a unique query parameter for all fields or a query language for filtering.

GET /api/v1/products?price>1000 Returns a list of products(Id, Name, Description, Code, Price), which price is greater than 1000

GET /api/v1/products?code=P123 Returns a list of products(Id, Name, Description, Code, Price) which code is "P123"

If you provide multiple filters, you can only return resources that match all filters.

5.4). Flexibility in field selection

The above get request gives a list of products along with all fields (ID, Name, Description, Code, Price). Let’s say, your API will be consumed by multiple users. Those users may be desktop, tablet, or mobile developers. Desktop users need all fields of products, tablet users need some fields and mobile users need only a few fields. They don’t need all the attributes of a resource all the time.

So, give the API consumer the ability to choose returned fields. This will also reduce the network traffic and speed up the usage of the API.

GET /api/v1/products?fields=name,price

It’ll give you only a list of products that contains name and price, not other fields (ID, description, and code)

5.5). Pagination

Paginate your API requests to limit response results and make them easier to work with. We use offset and count in the URL query string to paginate because it provides greater control over how you view your data.

/api/v1/products?offset=0&count=10

5.6). Sorting

Allow ascending and descending sorting over multiple fields.

  • GET /api/v1/products?sort=-price
    Retrieves a list of products in descending order of price
  • GET /api/v1/products?sort=+price,name
    Retrieves a list of products in ascending order of price and name

6. Security

Security is one of the most crucial parts of web API. Web API provides information about your functionality of business. Here, there is a chance hackers will misuse your API or steal your business information.

Hence you need to make sure, your methods are accessible to only authenticated users.

There are different types of authentication in web API.


1. Token-based authentication

Where the token is a random hash assigned to the user and they can reset it at any point if it has been stolen. Allow the token to be passed in through POST or an HTTP header.

2. OAuth 2

OAuth is a protocol; the current version is OAuth 2.0.DotNetOpenAuth provides implementations of both OAuth 1 and OAuth 2 and it's used to secure a .NET Web API.

OAuth flow starts where the registered user presents a username and password to a specific endpoint, and the API will validate those credentials, if everything is valid, it will return a token for the user where the client application used by the user should store it securely and locally to present this token with each request to any protected endpoint.

3. Token Generation

Choose a secure token, not a short numeric identifier or random string. Something irreversible is best.

Generate tokens by using JWT. JWT is lightweight and it has a payload. You can choose the algorithm type.

Generate tokens by using the SHA1 algorithm.

Finally, if a user is authenticated they can access the methods, if not it returns 401 unauthorized HTTP code.

7. Validation

I published an article about what will be the best way to validate the requests and how important it is.

8. HTTP Status Codes

Use the standard HTTP status codes to return controller actions.

Example

  • 400 – Bad Request: The request was invalid or validation failed.
  • 401 – Unauthorized: The request requires a user authentication.
  • 500 – Internal Server Error: Some exceptions or errors occurred in your action. So use 500 for failures.
  • 200 – OK: Everything is good.
  • 201 – OK: New resources have been created
  • 202 – Accepted: The request is accepted and it’s good for processing.

Pick a few good status codes and use them consistently and correctly throughout your API.

Don’t use 43 different status codes—use a few of the most commonly used ones. 200, 201, 302, 404, 400, 500, etc.

9. Web API helper page

I published an article with more about helper pages.

10. Logging

I published an article about advanced logging.

Conclusion

First, You should understand your requirements for API. Based on that you need to think more about the design and implementation of API. What are the things required for your API.