API and RESTful API are fundamental concepts that every programmer should be familiar with. When designing an API, there are some basic requirements that should be met to ensure efficient and effective interaction between systems.
If you're still unfamiliar with what an API is or havenāt grasped the concept of a RESTful API, take just 5 minutes to read on. I will explain everything in a straightforward and easy-to-understand manner.
ā What is an API?
- A simple example will make this clear:
- Back in 2000, online ticket purchasing began to emerge, but most people still relied on phone calls to inquire about flights. Initially, you would call your local station to ask for available flights or train schedules. After receiving the information, you would then go to the corresponding station to purchase your ticket.
With the rapid advancement of technology and the widespread use of smartphones, various travel Apps have surfaced, teaching everyone how to buy tickets through these apps.
Now, buying tickets has become much simpler. By entering your departure and destination in the App, you can see all relevant train and flight options. Not only do you get information about time and seat availability, but also details about the airline, expected duration, and much more, presented in a clear and concise manner. You can easily make your purchase based on your specific needs.
- Connection is a wonderful thing. In our current lives, we can effortlessly shop, read, and experience live broadcasts through various Apps, connecting with the world and people in unprecedented ways.
- So how is all this possible? What makes an App so convenient? How can information travel from point A to point B, allowing us to accomplish everything with just a swipe of our finger?
- The bridge enabling all thisāthe unsung hero of the internet worldāis the API. The full form of API is Application Programming Interface. In simple terms, it is an interface developed by brands that enables third parties to create additional functionalities and integrate them into their own products.
- Returning to the example provided earlier:
- In the old days, if we wanted to know flight information, we needed a messenger. The operator on the phone acted as this messenger, or what we call an API. They conveyed your request to the system. For instance, if you asked for flights to New York for the next day, the operator would retrieve that information and relay it back to you.
- Now, when we need to purchase plane tickets, we simply interact with a booking system where we can select dates, cities, and class preferences. This system gathers data from various airline websites, and the means through which it aggregates this information is via APIs that interact with the airlines.
- We now understand that it is APIs that enable our use of these travel Apps, and this principle applies universally to the interactions between applications, data, and devices across all aspects of life. Each of these systems uses its own API to establish connections with one another.
ā What is a RESTful API?
- In the early days of the internet, when it wasn't yet fully mainstream and mobile devices were not as prevalent, the demand for APIs was relatively low. At that time, web applications primarily operated on the server side, using complex protocols for data manipulation and transmission due to the limited volume of page requests and concurrent users.
- As the use of mobile devices surged, the necessity for accessing web applications from these devices became paramount. This shift marked a significant change in user behaviors and expectations, requiring a more efficient means of communication between client and server. Here, the role of APIs became critical, as they served as the bridge allowing mobile devices to interact seamlessly with web applications.
- Therefore, a set of APIs that is simplified for development, clearly structured, standardized, easy to understand, and extensible has become increasingly important for achieving widespread acceptance and usability. The RESTful API style perfectly embodies these characteristics, leading to its gradual emergence and popularity among developers and organizations.
REST
- REST, which stands for Representational State Transfer, is a design style and a software architectural style rather than a strict standard. It provides a set of design principles and constraints that guide the creation of networked applications. The goal of REST is to leverage the characteristics of the web, specifically the HTTP protocol, to create scalable and efficient services.
RESTful
- The term RESTful simply serves as an adjective to describe APIs or services that adhere to REST principles. For example, a RESTful API is an API that illustrates the characteristics and design constraints outlined by REST. It ensures that the API mimics a REST architecture, providing predictable and standardized interaction patterns.
RESTful API
- The common API we usually encounter looks like this:
- However, a RESTful API looks something like this:
š” Six Principles
- Roy Fielding is one of the main architects of the HTTP protocol. In his dissertation, he elaborated on the concept of REST architecture and outlined its six constraints, commonly known as the six principles. These principles serve as guidelines for building RESTful APIs and contribute to their functionality and scalability. Let's take a closer look at each principle:
Uniform Interface
- Just like the two illustrations we observed earlier, the most intuitive feature of an API is its adherence to the principles of the REST architecture. A unified interface is crucial for RESTful services. Clients only need to focus on implementing the interface, which enhances the readability of the API and makes it convenient for users to access.
-
The RESTful API locates resources via URLs and manipulates these resources through HTTP methods. The operations on resources include fetching, creating, updating, and deleting, which correspond directly to the HTTP protocols GET, POST, PUT, and DELETE.
- GET: Retrieve resource information.
- POST: Create a new resource.
- PUT: Update an existing resource.
- DELETE: Remove an existing resource.
-
Within a team that fully adheres to RESTful principles, the backend only needs to inform the frontend about the /users API, and the frontend should inherently understand the following operations:
- Obtain all users: GET /users
- Retrieve a specific user: GET /users/{id}
- Create a new user: POST /users
- Update an existing user: PUT /users/{id}
- Delete a user: DELETE /users/{id}
As the number of APIs grows and the system becomes increasingly complex, the advantages of RESTful architecture become more pronounced. Understanding the system can be streamlined by focusing on a series of resources, which aids in comprehension and memory retention.
Client-Server
- This means that the client and server are independent and can be decoupled from one another.
- The client is responsible for requesting and processing data, while the server is responsible for storing data and handling requests.
- These two components collaborate through a set of conventions to ensure that the client can fetch the data it needs efficiently.
Statelessness
- This refers to the principle that each request is independent and has no relationship with previous requests. The server does not maintain any state information about the client, and each request must contain all the necessary information to process it.
- The benefit of this approach is that it simplifies each request, making it easy to understand and handle, as well as enabling easier scaling and maintenance.
- For instance, consider a scenario where you are logging into a website. You enter your username and password on the login interface and obtain a token through an API. From that point onward, all subsequent requests must carry this token instead of the system keeping track of your logged-in status after the first successful login.
Cacheability
- Clients and servers can negotiate cacheable content, allowing servers to inform clients whether specific data can be cached by setting appropriate HTTP status codes.
- For instance, an HTTP response may include a Cache-Control header, which communicates to the client how long the data can be cached. This increases the efficiency of data transmission, reduces network bandwidth usage, and accelerates data access speeds. By effectively managing cached content, applications can offer users faster response times and a more seamless experience.
Layered System
Clients should not worry about how many intermediary layers a request traverses; their main focus should be on the outcome of the request. A well-designed architecture can be divided into multiple layers, with each layer independently responsible for completing its specific tasks. This layered approach results in a system that is easier to maintain and allows for the independent replacement or enhancement of various layers.
For instance, the database storage layer can function independently from other layers in the architecture. This independence enables developers to replace or extend the database layer without impacting the operation of other layers. Such modularity not only streamlines the development process but also enhances the overall resilience and scalability of the system.
Code on Demand
Clients should not be concerned with how many intermediary layers a request passes through; they need only focus on the outcome of the request.
The architecture of the system can be divided into multiple layers, each responsible for completing its own tasks. This layered structure makes the system easier to maintain and allows for the independent replacement of different layers.
For instance, the data storage layer can operate independently of the other layers. This means it can be replaced or expanded without affecting the functionality of the other layers. Such modularity fosters better maintainability and scalability within the application architecture.
š„ RESTful API Design Guidelines
- Having discussed the theoretical aspects of RESTful APIs, itās time to turn our attention to the practical side: how can we design the simplest RESTful style API?
HTTP Methods
- HTTP has designed various verbs to signify different actions, and each HTTP request method has its own significance. As demonstrated above, a RESTful API should employ HTTP methods (such as GET, POST, PUT, and DELETE) to describe operations on resources.
Versioning
-
Versioning refers to updating a RESTful API without affecting existing client applications. Common versioning methods include:
- URL Method: By changing the URL to indicate different versions, such as https://api.example.com/api/v1/resources and https://api.example.com/api/v2/resources.
- Accept Header: Using the Accept field in the request headers to indicate the desired version of the API.
- Request Parameters: Specifying the version through request parameters, such as https://api.example.com/resources?version=1 and https://api.example.com/resources?version=2.
-
Different companies and teams may implement various approaches to API design, but I believe keeping the versioning method as simple and intuitive as possible is essential. Placing the version directly in the URL is straightforward and clear, making it easier for developers to understand and use.
URLs Clearly Identify Resources
An API should utilize concise and clear URLs to identify resources while employing different HTTP methods to perform various operations on the same resource.
This design enables clients to locate the required resources without the need for additional information or extensive documentation. Clear URLs provide a straightforward way for clients to interact with the API effectively.
In contrast, irregular URLs can come in many forms, requiring different developers to dive into documentation to understand how to interact with them. Unstructured URLs may lead to confusion and inefficiencies in development.
Adhering to a standardized RESTful style in URLs results in fixed formats that enhance readability. By relying on clear nouns and corresponding HTTP verbs, developers can easily operate on resources, facilitating a more intuitive experience when working with the API.
-
Hereās a little tip: If you ever find yourself struggling to come up with a suitable URL, you can refer to the GitHub Open API. It features a wealth of well-structured and organized URL designs.
HTTP Status Codes
-
HTTP
status codes are a crucial part ofRESTful API
design, serving to indicate the status of anAPI
request and informing the client whether the request was successful and if the data was processed correctly. Some commonly usedHTTP
status codes include:- 200 OK: The request was successful, and the requested data has been retrieved.
- 201 Created: The request was successful, resulting in the creation of a new resource.
- 204 No Content: The request was successful, but there is no data to return, indicating that the operation was completed.
- 400 Bad Request: The request failed due to incorrect formatting or missing required parameters.
- 401 Unauthorized: The request failed due to authentication issues or lack of authorization.
- 403 Forbidden: The request failed because the client does not have permission to access the resource.
- 404 Not Found: The request failed because the requested resource does not exist.
- 500 Internal Server Error: The request failed due to an internal server error.
These status codes help clients understand the outcome of their requests and allow developers to handle errors and success scenarios effectively.
Unified Return Data Format
-
Commonly used return data formats for
RESTful APIs
includeJSON
andXML
.- JSON (JavaScript Object Notation) is currently a popular data format due to its simplicity, lightweight nature, and ease of parsing. Its readability makes it especially favored in web applications, where data interchange between a server and a client is frequent.
- XML (eXtensible Markup Language) is another widely used data format. Its strengths lie in its flexibility and support for various data types. XML can represent complex data structures and is sometimes preferred in scenarios that require document validation or a more descriptive format. ##### Well-Structured and Aesthetic API Documentation
In any project development, especially when implementing a separation of frontend and backend, APIs play a vital role. Consequently, this reliance on APIs naturally extends to the importance of maintaining updated and comprehensive API documentation. However, many programmers find creating documentation to be tedious, and I've even come across scenarios where a company's API documentation was painstakingly crafted using a Word document.
Fortunately, there are many tools available in the market designed specifically for managing and documenting APIs. Each developer or team may have their own preference, but Iād like to recommend a remarkable API management tool called Apidog. This tool allows you to generate API documentation with just a few clicks.
The best part about Apidog is that it simplifies the documentation process significantly. You donāt need to perform numerous operationsāsimply add your APIs through a user-friendly visual interface, and the tool will automatically generate the documentation for you.
š Final Thoughts
In summary, while
RESTful
style APIs are indeed effective and well-structured, many internet companies do not strictly adhere to its guidelines when designing their APIs. This is becauseREST
is more of a style than an inflexible set of rules; overly idealistic implementations ofRESTful APIs
can lead to significant costs and complexities.If you are considering the use of
RESTful APIs
, ensure that they align with your business needs. For example, if your project requires intricate data interactions, you might need to explore alternative API design methodologies that better accommodate those requirements.Therefore, it is crucial to thoroughly consider your business needs when selecting an API design approach. Additionally, ensure that the
RESTful API
is compatible with your system architecture and technology stack. These considerations will help guarantee the proper utilization ofRESTful APIs
, ultimately leading to more efficient and reliable API performance.In the long run, API design should not be viewed as solely the responsibility of the backend team; it should be a collaborative effort involving coordination among the entire product team during the product design process. A well-rounded approach ensures that all aspects of API usageāfrom usability to functionalityāare taken into account.
This brief overview of APIs and
RESTful APIs
emphasized that while it is not mandatory to strictly implement these standards, having a reference likeRESTful
guidelines is invaluable. Such guidelines can provide essential insights and best practices, which can significantly enhance the design and efficiency of your APIs. Hopefully, this information proves helpful to everyone in their journey of API development and implementation.
š References
[1]GitHub Open API:https://docs.github.com/en/rest/actions/artifacts
[2]Apidog: https://apidog.com/
Top comments (5)
Good stuff! There was duplication under layered system and code on demand.
We've built Vratix exactly for this reason - open source API modules that are easy to use, robust and extensible, we build them following the latest best practices so you don't end up with technical debt!
Didn't know about vratix so far, but it looks very promising! Added it to the next issue of weeklyfoo.com
Great overview! Would be great to have some kind of a cheat sheet as a one pager with these best practices.
Great read! Very helpful for me, thank you š
Some comments may only be visible to logged-in visitors. Sign in to view all comments.