CategoryTagArticle

admin

I'm a Full-stack developer

Tag

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
RESTful API - How to design?
Published date: 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/
Recommend

NodeJS Verify and Decode Cognito JWT Tokens
admin12/06/2023

NodeJS Verify and Decode Cognito JWT Tokens
In this article, I will show you how to verify and decode the Cognito JWT Tokens token.
How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
How to integrate ChatGPT-3.5 Turbo into Node.js
admin10/01/2024

How to integrate ChatGPT-3.5 Turbo into Node.js
Step-by-Step Guide to Incorporating ChatGPT-3.5 Turbo into Node.js for Basic ReactJS Applications
Newest

Create S3 Bucket with AWS CDK
admin09/06/2023

Create S3 Bucket with AWS CDK
In this article, I introduce Amazon CDK and how to write AWS infrastructure-as-code using TypeScript. We will do it step by step.
Difference Between Stack and Queue
admin07/04/2024

Difference Between Stack and Queue
In the fundamental data structure, besides the linked list, the stack and queue are also used widely in computer science and programming.
TypeScript Design Pattern - Proxy
admin11/08/2023

TypeScript Design Pattern - Proxy
Provide a surrogate or placeholder for another object to control access to it.
Đ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
Feedback
Name
Phone number
Email
Content
Download app
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About