48  
bestpractices
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Feb 7, 2021

Web API design principles or Web API design guidelines

Автор:
Manikanta Pattigulla
Источник:
Просмотров:
6751

Overview

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

How to design or build great Web API Applications?

Basically 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 very important for Web API’s because in this, each method is describing two things i.e., what it’ll accept and what it’ll provide.

As a developer, I worked on consuming several external web API’s like mail chimp, klaviyo, sales force, bronto and etc. these all are email service providers.

My Requirement is to get a list of emails from each web API. I have many API's 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 API is doing and how I can get the result then it’s a great API because of well marked documentation.

A few API's 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 API's 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 own state of behavior. Don’t change or mix their state.

 

GET

POST

PUT

DELETE

RESOURCE

Read

Create

Update

Delete

Example for 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 which is using the API, those changes should be introduced in a new version of the API.

Every developer should do some planning ahead of your 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, if you have a lot of users for your web API, users may needed output as 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 flexible (about input, 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 are giving 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 on 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 on 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 few fields. They don’t need all 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 gives you only list of products which 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 important and crucial parts in 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 should be accessible to only authenticated users.

There are different types of authentication in web API.

  • 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.
     
  • OAuth 2:

    OAuth is a protocol; the current version is OAuth 2.0.DotNetOpenAuth which 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 will present username and password to a specific end point, and the API will validate those credentials, and 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 in order to present this token with each request to any protected end point.

Token Generation:

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

Generate token by using JWT. JWT is lightweight and it has pay load. You can choose algorithm type.
Generate token by using SHA1 algorithm.

Finally, if 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 exception or error occurred in your action. So use 500 for failures.
200 – OK – Everything is good.
201 – OK – New resources has been created
202 – Accepted – 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. [c]

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 design and implementation of API. What are things really required for your API.

Похожее
Jul 8, 2021
Author: Christophe Nasarre
In the context of helping the teams at Criteo to clean up our code base, I gathered and documented a few C# anti-patterns similar to Kevin’s publication about performance code smell. Here is an extract related to good/bad memory patterns....
Aug 14
Author: Yasith Wimukthi
In today’s fast-paced development environment, Docker has become a vital tool for developers, simplifying the process of creating, deploying, and running applications in containers. However, to truly harness the power of Docker, it’s crucial to follow best practices that ensure...
Aug 8
Author: Anton Martyniuk
Integration testing is a type of software testing essential for validating the interactions between different components of an application, ensuring they work together as expected. The main goal of integration testing is to identify any issues that may arise when...
Mar 18
Author: codezone
File reading operations in C# are crucial for many applications, often requiring efficiency and optimal performance. When handling file reading tasks, employing the right strategies can significantly impact the speed and resource utilization of your application. Here are some best...
Написать сообщение
Тип
Почта
Имя
*Сообщение