REST API: A Practical Guide to Creating APIs the Right Way

REST API: A Practical Guide to Creating APIs the Right Way
ibnu gunawan prayogo

Ibnu Gunawan P

Tue, 16 2023, 2:11:00 am

Table Of Content

REST API: A Practical Guide to Creating APIs the Right Way

Hello there! Today, I want to share a bit about REST API, something I've learned along the way 😁. So, what exactly is REST API, and how can we create a good and proper REST API?

Introducing Rest API

Let's start with a simple analogy. Imagine using an ATM machine to access your bank account. The ATM serves as an interface (API) that helps you connect to the bank's system. You can request to check your balance or make a withdrawal, and the ATM processes these requests and provides responses accordingly. The API here is responsible for managing access to your bank account and offering a standardized way to interact with the bank's system without needing to know its internal workings. This is a basic example of how REST API operates in the context of banking.

REST API, also known as Representational State Transfer Application Programming Interface, is an approach used to connect and integrate systems or applications. In a REST API, applications can communicate with each other through HTTP requests such as GET, POST, PUT, and DELETE. Commonly, data is sent and received in formats like JSON.

Creating the Right REST API

Before diving into creating a REST API, there are a few rules to follow. First, design your API clearly by defining a consistent endpoint structure. Next, use the appropriate HTTP methods like GET, POST, PUT, and DELETE according to the intended processes. It's crucial to provide clear responses for each request, including the use of the correct HTTP status codes. Implement authentication and authorization to protect your API from unauthorized access. Additionally, make sure to provide meaningful error messages in case of mishaps. Supply documentation that is user-friendly for clients or front-end developers. Finally, regularly monitor your API to ensure it performs as intended. Here's a more detailed breakdown of how to create a REST API.

Defining API Design

This step requires defining a solid API design before implementation. Understand the business requirements, what programming language and database you'll need, and design suitable endpoints.

Structuring Endpoints

The structure of endpoints in a REST API is the pattern or format used to create URLs that lead to specific processes within the API. Endpoint structures help guide what processes are available in the API.

An endpoint consists of several components, including the domain or host, path (URL location), and optional parameters. The path delineates the hierarchy or categories within the API, while parameters are used to specify more specific requests.

Examples of Endpoint Structures:

  • GET /api/users: Retrieve a list of users from the API.
  • POST /api/users: Create a new user in the API.
  • GET /api/users/{id}: Retrieve user information based on a specific ID.
  • PUT /api/users/{id}: Update user information based on a specific ID.
  • DELETE /api/users/{id}: Delete a user based on a specific ID.

With a well-structured endpoint, API users can easily understand how to access resources or perform specific tasks within the API.

Choosing the Right HTTP Methods

HTTP methods are crucial in creating a REST API as they provide different operations on the accessed endpoints. Each HTTP method has distinct meanings and purposes and is used to identify the process to be carried out.

Here are some commonly used HTTP methods in REST API creation:

  1. GET: Typically used to fetch or retrieve data from the server without altering existing data.
  2. POST: Used to send data to the server for processing, such as logging in with a username and password or adding new entries to a database.
  3. PUT: Used to update or replace existing data on the server with the data sent by the client. With PUT, you can send data to replace what's currently stored.
  4. DELETE: Used to initiate the deletion of specific data on the server. When DELETE is used, the requested data, identified by the provided URL or query, will be removed.
  5. PATCH: Used to partially update existing data on the server. Unlike PUT, PATCH only updates the parts of data that have changed, without replacing the entire dataset.

Using the Right Status Codes (HTTP Status)

HTTP status codes are crucial in creating a REST API as they provide information about the status of requests made by applications or clients to the server. HTTP status consists of three-digit numbers sent by the server as a response to a request. Here are some commonly used HTTP status codes:

Status Code Explanation
200 [ OK ] Indicates a successful request, and the server will provide the expected response. This is the most common status for successful requests.
201 [ Created ] Signifies that the server has successfully created new data, such as processing new data to be stored in a database after a POST request.
204 [ No Content ] Indicates that the server has processed the request but is not returning content in the HTTP response. Typically used for requests that do not require content in the response.
400 [ Bad Request] Indicates that the request sent contains incorrect or incomprehensible data. This can occur due to formatting errors or invalid data.
401 [ Unauthorized ] Indicates that the requested API access requires authorization. The request must provide valid credentials, such as a username, password, token, or API key, to access the API.
403 [ Forbidden ] Indicates that the server understood the request but refused to fulfill it. This might involve restrictions on accessing specific files or denying access based on the client's IP address.
500 [ Internal Server Error ] This is a common response indicating that the server has encountered an error or crash, preventing it from processing the request correctly. It may also indicate server issues.
503 [ Service Unavailable ] Signifies that the server cannot handle the request at the moment due to high traffic or undergoing maintenance. It's advisable to provide a notice for the client to try again later.

Note: The above HTTP statuses are just a few common examples that I use. There are many other HTTP statuses that can be used depending on the communication needs between the client and server via the HTTP protocol. For a more comprehensive list, you can check here.

Specifying Content Types (Content-Type)

Content-Type is an HTTP header used to specify the response type of data being sent or received through API requests or responses. Some common Content-Type examples in REST APIs include:

  1. application/json: Indicates that data is sent or received in JSON (JavaScript Object Notation) format.
  2. application/xml: Specifies that data is sent or received in XML format (eXtensible Markup Language).
  3. application/x-www-form-urlencoded: Used for sending data in URL-encoded format, commonly used in POST or PUT requests from HTML forms.
  4. multipart/form-data: Used for sending data containing files in POST or PUT requests.

text/plain: Specifies that data is sent or received in plain text format. When sending or receiving data via a REST API, it's essential to specify the appropriate Content-Type header so users can understand and process data correctly.

Handling Errors

When creating an API, it's important to handle errors effectively. If an error occurs when a user of the API makes a request, provide valuable information in the API response. This can include clear error messages and associated error status codes. Here's an example of an API response in JSON format:

HTTP/1.1 200 OK
Content-Type: application/json

{
	"status": false,
	"message": "User or customer not found"
}

Documentation

Documentation is a critical step in the creation of a REST API.

API documentation explains how to use the API, including the required parameters, available endpoints, methods, and the data that can be sent by API users, as well as the format of the responses. Good documentation helps API users understand and integrate the API correctly. A common tool I use for creating and managing API documentation is Postman.