Danh mụcThẻBài viết

admin

I'm a Full-stack developer

Thẻ

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
RESTful API - How to design?
Ngày đăng: 09/06/2023


In this article, I will describe the useful points of designing a good API.

Designing a good API is really not easy, building a good API enhances the value of your service. Because today, the services or platforms of big companies like Facebook, Google, Amazon, ... are communicating with each other through APIs.


What is an API?


API stands for Application Programming Interface. In the context of APIs, the word Application refers to any software with a distinct function. The interface can be thought of as a contract of service between two applications. This contract defines how the two communicate with each other using requests and responses. Their API documentation contains information on how developers are to structure those requests and responses.


What are REST APIs?


REST stands for Representational State Transfer. REST defines a set of functions like GET, PUT, DELETE, etc. that clients can use to access server data. Clients and servers exchange data using HTTP.


What are RESTful APIs?


RESTful API is a standard used in the design of APIs for web applications to manage resources. RESTful is one of the popular API design styles used today to let different applications (web, mobile...) communicate with each other.


HTTP Methos


REST works mainly on the HTTP protocol. The table below lists the standard methods that correspond to specific actions for resources.


| Method | Action             | Description
| ------ | ------------------ |
| Get    | Selec              | Returns a resource or list of resources
| Post   | Create             | Create a new resource
| Put    | Update             | Update information for resources
| Path   | Update             | Updating an ingredient, a resource's properties.
| Delete | Delete             | Delete a resource


Use plural nouns


Use plurals for consistent URL formatting. Share a controller, and actions are separated by methods.


GOOD


| Method | API                | Description
| ------ | ------------------ |
| GET    | /users             | Return user list
| GET    | /users/1           | Return user information who has id equals 1
| GET    | /users/1/address   | Return user address who has id equals 1
| GET    | /users/1/address/2 | Return user address with id equals 2 who has id equals 1
| POST   | /users             |
| POST   | /users/1/address   |
| PUT    | /users/1           |
| PUT    | /users/1/address   |
| DELETE | /users/1/address/2 |


BAD
| Method | API                
| ------ | ------------------ 
| GET    | /getAllUsers        
| POST   | /createNewUsers     
| DELETE | /deleteUsers/1      


API versioning


Using the version in the API will avoid being affected by changes to the existing service when new changes are made. Because the API will be constantly updated and changed to suit the company's business situation.

I have 2 options for API versioning as below, which is the most perfect choice:

(1) https://dinhthanhcong.com/api/v1

(2) https://api.dinhthanhcong.com/v1

The two options above are good for version design. But, in case your application is large. The design under a subdomain (2) is the most perfect, it can help you reduce the page load.


Filter, sort, search, and pagination

Filter: use a single variable:
// Returns a list of active users
GET /users?status=activate


Sort: use "sort_fields" and "sort" parameters
// Returns a list of users sorted by creation time
GET /users?sort_fields=created_date&sort=desc
GET /users?sort_fields=created_date&sort=asc


Search: sometimes using filter conditions is not enough
// Returns a list of users with the last name is "đinh"
GET /users?keyword=đinh


Limit return data
// Returns a list of users with the required information being first and last name
GET /users?select=firstname,lastname


Pagination: using limit and offset
GET /users?offset=10&limit=20


Response data

Successfully
{
    "statusCode": 2001,
    "status": 200,
    "message": "User is created.",
    "data": {
        "id": 1,
        "email": "thanhcong240295@gmail.com",
    }
}


Failure
{
    "statusCode": 4001,
    "status": 400,
    "message": "Invalid request",
    "data": {
        body: [
            "Email must be a valid email",
            "Password must be at least 8 characters"
        ]
    }
}


Commonly used HTTP codes


| HTTP Code | Status                | Description
| --------- | --------------------- |
| 200       | OK                    | Returns success for GET, PUT, PATCH, and DELETE methods
| 201       | Created               | Resource created successfully
| 204       | No Content            | Resource deleted successfully
| 400       | Bad Request           | The data sent from the client is invalid
| 401       | Unauthorized          | Request is not authenticated
| 403       | Forbidden             | Request denied because access is not allowed
| 404       | Not Found             | Resource not found
| 422       | Unprocessable Entity  | Data not checked
| 429       | Too Many Requests     | Limit the number of requests
| 500       | Internal Server Error | The server is having an error


Summary


Try to design a good API, because it's not just functionality, but makes it easy for users to use.


--------------------------------

Reference documents:

  1. https://aws.amazon.com/what-is/api/
Đề xuất

Part 1: How to deploy Ghost Blog on AWS using Lightsail
admin17/06/2023

Part 1: How to deploy Ghost Blog on AWS using Lightsail
In this article, I want to introduce about how to deploy Ghost Blog on AWS using Lightsail.
TypeScript Design Pattern - Bridge
admin08/08/2023

TypeScript Design Pattern - Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
What are the SOLID principles?
admin17/06/2023

What are the SOLID principles?
If we want to have good software, the infrastructure should be good first. We should learn more techniques that help to have better quality.
Mới nhất

Microservice in a Monorepo
admin22/06/2023

Microservice in a Monorepo
Microservice in a Monorepo
JOI - API schema validation
admin12/06/2023

JOI - API schema validation
Data validation is one of topics that I am interesting. I always review my code after developed features or fixed bugs. There are many places where need to validate data, it is really terrible. Some cases, we need to validate data input because ensure the data into API, it will not make any problems to crash system.
Part 1: How to deploy Ghost Blog on AWS using Lightsail
admin17/06/2023

Part 1: How to deploy Ghost Blog on AWS using Lightsail
In this article, I want to introduce about how to deploy Ghost Blog on AWS using Lightsail.
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Góp ý
Họ & Tên
Số điện thoại
Email
Nội dung
Tải ứng dụng
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About