Introduction
In backend development, building an API is not just about creating
endpoints that allow a frontend to communicate with a server.
A well-designed API should be predictable, consistent, maintainable, and
easy for other developers to understand and integrate with.
Imagine building an e-commerce application. It needs to support
operations such as:
- Registering and managing users.
- Displaying products.
- Creating and tracking orders.
- Processing payments.
- Managing deliveries.
We could create endpoints for all these operations in different ways.
However, without a consistent approach, the API can quickly become
difficult to maintain.
This is where REST API design becomes important.
REST provides a set of architectural principles that help us design APIs
around resources, standard communication methods, and predictable
interactions between clients and servers.
In this blog, we'll understand REST from its foundations and gradually
explore how to design APIs that are consistent and scalable.
1. History and Core Constraints of REST
To understand REST, let's first look at how the modern web evolved.
A brief history of the web
In 1990, Tim Berners-Lee invented the World Wide Web (WWW) to make
sharing and accessing information across the world easier.
The early web ecosystem introduced several important concepts and
technologies:
- URI (Uniform Resource Identifier): A way to identify resources.
- HTTP (Hypertext Transfer Protocol): A communication protocol between clients and servers.
- HTML (Hypertext Markup Language): A standard format for representing web documents.
- Web Servers: Systems responsible for hosting and delivering resources.
- Web Browsers: Applications used to access and interact with web resources.
- WYSIWYG Editors: Tools that allowed users to create content visually (What You See Is What You Get).
As the web grew, the number of users, resources, and interactions
increased significantly.
This introduced a major challenge: How could the web continue to scale
while remaining reliable and maintainable?
In the early 1990s, Roy Fielding worked on architectural principles for
the web. He later formalized the REST (Representational State Transfer)
architectural style in his doctoral dissertation.
REST describes a set of constraints that help build scalable
network-based applications.
The six REST architectural constraints
REST is based on six architectural constraints.
1. Client-Server Architecture
The client and server have separate responsibilities.
- Client: Handles the user interface and user interactions.
- Server: Handles business logic, data processing, and data storage.
For example, in an e-commerce application:
- The frontend displays products and collects user input.
- The backend retrieves products from the database and returns the required information.
This separation allows both sides to evolve independently.
2. Uniform Interface
The client and server should communicate through a consistent interface.
This constraint has four important elements:
- Resource Identification: Every resource should have a unique identifier, usually a URI.
- Resource Manipulation Through Representations: Clients interact with resources using representations of those resources.
- Self-Descriptive Messages: Requests and responses should contain enough information to explain how they should be interpreted.
- Hypermedia as the Engine of Application State (HATEOAS): Responses can contain links that guide clients toward available actions and related resources.
The purpose is to make communication consistent rather than requiring
every API to follow a completely different interaction pattern.
3. Layered System
A client should not need to know whether it is communicating directly
with the application server or through intermediate layers.
For example:
Client | v Load Balancer | v API Gateway | v Application Server | v Database Each layer has its own responsibility.
This architecture allows us to introduce security, load balancing,
caching, and other infrastructure without changing how the client
communicates with the API.
4. Caching
Responses should indicate whether they can be cached.
Caching allows frequently requested data to be reused instead of
repeatedly fetching it from the server.
For example, product category information may not change frequently. It
can be cached to reduce unnecessary requests and improve performance.
5. Statelessness
Every request should contain the information necessary for the server to
process it.
The server should not depend on remembering the client's previous
request to understand the current one.
For example, when a user accesses a protected endpoint, the request
should include the required authentication credentials or token.
The server validates them independently for that request.
Statelessness makes it easier to distribute requests across multiple
servers.
6. Code on Demand (Optional)
The server can optionally send executable code to the client.
For example, a web application may receive JavaScript that the browser
executes.
This constraint is optional in REST.
2. Understanding the REST Principle
The term REST stands for Representational State Transfer.
Let's break it into three parts.
2.1 Representational
A resource can have different representations depending on the client's
requirements.
For example, consider a product resource:
{ "id": 101, "name": "Wireless Headphones", "price": 2499, "inStock": true } The same resource could be represented in JSON, XML, or another
supported format.
The important idea is that the resource itself is separate from the
representation used to communicate it.
2.2 State
State refers to the current condition of a resource or application.
Consider an Amazon-like shopping cart.
Initially:
{ "cartId": 1, "items": [] } After adding a product:
{ "cartId": 1, "items": [ { "productId": 101, "quantity": 1 } ] } The state of the cart has changed because a product was added.
2.3 Transfer
Transfer refers to the movement of resource representations between the
client and server.
For example:
- The client requests product information.
- The server retrieves the product.
- The server sends its representation to the client.
- The client displays the information.
Therefore, REST describes how representations of resources are exchanged
while the application operates.
3. URL Structure and Resource Naming
URLs are one of the most important parts of API design.
A well-designed URL should communicate which resource the client wants
to access.
Consider this URL:
https://api.example.com/v1/products/123?sortBy=price#details Let's understand its components:
Component Example Purpose
Protocol https:// Communication protocol
Subdomain api Identifies the API service
Domain example.com Domain name
Version v1 API version
Resource products Resource collection
Path parameter 123 Identifies a particular product
Query parameter sortBy=price Controls the requested result
Fragment #details Identifies a section within the resource
Resource naming conventions
When designing REST APIs, resource names should follow consistent
conventions.
1. Use nouns instead of verbs
Prefer:
GET /products POST /products DELETE /products/123 Avoid:
GET /getProducts POST /createProduct DELETE /deleteProduct/123 HTTP methods already describe the action, so the URL should primarily
identify the resource.
2. Use plural resource names
Prefer:
/products /users /orders /authors Even when accessing a single resource, retain the plural resource name:
GET /products/123 GET /users/45 3. Use nested resources when relationships are meaningful
For example:
GET /users/45/orders GET /orders/123/items This makes the relationship between resources clear.
4. Use hyphens for multiword resource names
Prefer:
GET /delivery-partners Avoid inconsistent naming styles such as:
GET /deliveryPartners GET /delivery_partners 5. Use path parameters to identify specific resources
GET /products/123 Here, 123 identifies the particular product.
6. Version your APIs
For example:
/api/v1/products /api/v2/products Versioning allows an API to evolve while maintaining compatibility for
existing clients.
4. HTTP Methods and Idempotency
HTTP methods describe what operation the client wants to perform on a
resource.
The commonly used methods are:
Method Purpose Example
GET Retrieve a resource Fetch products
POST Create a resource or trigger an operation Create an order
PUT Replace a resource Replace product details
PATCH Partially update a resource Update product price
DELETE Remove a resource Delete a product
Let's understand an important concept associated with these methods.
What is idempotency?
Idempotency means that performing the same operation multiple times has
the same intended effect on the server as performing it once.
For example, consider this request:
PUT /users/45 Request body:
{ "name": "Alex", "email": "alex@example.com" } Whether we send this request once or five times, the resulting user
representation remains the same.
This is an idempotent operation.
Which HTTP methods are idempotent?
HTTP Method Idempotent? Explanation
GET Yes Repeated requests do
not change server state
PUT Yes Replaces the resource
with the same intended
representation
DELETE Yes Repeated deletion has
the same intended final
effect
POST No, generally Repeated requests may
create multiple
resources
PATCH Not necessarily Depends on the
operation being
performed
An important distinction: PATCH can be designed to be idempotent, but
the HTTP method itself does not guarantee it.
Why is idempotency important?
Imagine a payment request.
A user clicks the payment button, but the network connection fails
before the response reaches the client.
The client does not know whether the payment was processed.
If it blindly retries the request, the user might be charged twice.
This is why APIs often use idempotency keys for operations such as
payment creation.
Example:
POST /payments Idempotency-Key: payment-abc123 The server can use this key to recognize retries of the same logical
operation and avoid processing it more than once.
When should we use POST?
POST is commonly used to create resources.
However, not every operation fits neatly into GET, PUT, PATCH, or
DELETE.
For example:
- Sending an email.
- Triggering a password reset.
- Initiating a payment.
- Generating a report.
These operations may use POST because they trigger an action or process.
When an operation does not naturally represent retrieving, replacing,
partially updating, or deleting a resource, POST is often appropriate.
5. REST API Design Workflow
Before writing API endpoints, we should understand what the application
needs.
Let's use an e-commerce application as our example.
Step 1: Understand the frontend requirements
Start by examining how the frontend uses data.
Ask questions such as:
- What information does each page require?
- Which operations can users perform?
- What data should be displayed?
- What information must be submitted to the backend?
For example, a product listing page may require:
- Product name.
- Product image.
- Price.
- Availability.
- Category.
Understanding these requirements helps us determine what the API should
provide.
Step 2: Identify resources and define their schemas
After understanding the requirements, identify the main resources.
For an e-commerce application, these might include:
- Users
- Products
- Sellers or vendors
- Orders
- Delivery partners
- Analytics
Once we identify the resources, we define their data structures.
For example, a Product resource:
{ "id": 101, "name": "Wireless Headphones", "description": "Noise-cancelling headphones", "price": 2499, "categoryId": 10, "inStock": true, "createdAt": "2026-12-01T10:00:00Z" } Defining schemas gives us a clear understanding of the information each
resource contains.
Step 3: Define actions on the resources
Now identify the operations that users can perform.
These generally follow CRUD:
- Create: Add a new resource.
- Read: Retrieve an existing resource.
- Update: Modify an existing resource.
- Delete: Remove a resource.
For example:
Operation HTTP Method Endpoint
Create product POST /products
Get all products GET /products
Get one product GET /products/101
Update product PUT /products/101
Partially update product PATCH /products/101
Delete product DELETE /products/101
This gives us a clear API contract before implementation begins.
Step 4: Design the API interface
Now define how the frontend will interact with the backend.
For every endpoint, determine:
- URL path.
- HTTP method.
- Required headers.
- Query parameters.
- Path parameters.
- Request body.
- Expected response body.
- Appropriate HTTP status codes.
For example:
Endpoint:
POST /api/v1/products Headers:
Content-Type: application/json Authorization: Bearer <token> Request body:
{ "name": "Wireless Headphones", "price": 2499, "categoryId": 10 } Expected response:
{ "id": 101, "name": "Wireless Headphones", "price": 2499, "categoryId": 10 } For documenting and testing APIs, we can use tools such as:
- Swagger / OpenAPI.
- Postman.
- Insomnia.
Frameworks such as FastAPI also provide built-in Swagger UI and ReDoc
documentation.
Having a clearly defined interface allows frontend and backend
developers to work independently.
6. Pagination and Sorting
Imagine an e-commerce application containing 100,000 products.
If the frontend requests all products in a single API call, the server
may need to process and transfer a huge amount of data.
This can result in:
- Increased response time.
- Higher memory consumption.
- Increased network usage.
- Poor user experience.
To address this, we use pagination.
What is pagination?
Pagination is the process of dividing a large collection of data into
smaller chunks or pages.
Instead of retrieving all 100,000 products, the client requests only a
limited number at a time.
For example:
GET /products?page=1&limit=10 This requests the first page containing 10 products.
GET /products?page=2&limit=10 This requests the next 10 products.
A typical pagination structure includes:
Parameter Purpose Example
page Requested page number 1
limit Number of records per page 10
The server calculates the offset using:
offset = (page - 1) * limit For page 3 with a limit of 10:
offset = (3 - 1) * 10 offset = 20 The server skips the first 20 records and retrieves the next 10.
Pagination response
A well-structured paginated response can include metadata:
{ "data": [ { "id": 101, "name": "Wireless Headphones", "price": 2499 } ], "pagination": { "page": 1, "limit": 10, "totalItems": 100, "totalPages": 10 } } What is sorting?
Sorting allows clients to control the order in which resources are
returned.
For example:
GET /products?sortBy=price&sortOrder=asc This retrieves products sorted by price in ascending order.
Another example:
GET /products?sortBy=createdAt&sortOrder=desc This retrieves the newest products first.
Providing default values
Pagination and sorting parameters should be optional.
If the client does not provide them, the server should use sensible
defaults.
For example:
page = 1 limit = 10 sortBy = createdAt sortOrder = desc We should also validate the values.
For example:
- Page numbers should be positive.
- Limits should have a reasonable maximum.
- Sorting fields should belong to an allowed list.
- Sort order should accept only supported values.
This prevents invalid requests and protects server resources.
7. Filtering
Pagination and sorting control how data is returned. Filtering
determines which data should be returned.
Imagine the user wants to find delivered orders.
We can design an endpoint like:
GET /orders?status=delivered Here, the status query parameter filters the orders.
Another example:
GET /products?productName=mobile This retrieves products matching the specified product name.
We can also combine multiple filters:
GET /products?category=electronics&minPrice=1000&maxPrice=5000 This requests products that match the specified category and price
range.
Why use query parameters for filtering?
Query parameters are useful because they allow clients to dynamically
customize the results without creating separate endpoints for every
possible combination.
For example, we don't need endpoints such as:
/products/electronics /products/electronics/under-5000 /products/electronics/above-1000 Instead, we can use:
GET /products?category=electronics&minPrice=1000&maxPrice=5000 This keeps the API simpler and more flexible.
8. HTTP Status Codes and Response Bodies
Whenever an API processes a request, it should return an appropriate
HTTP status code and response body.
Status codes communicate the outcome of an operation to the client.
Common success status codes
Status Code Meaning Typical Usage
200 OK Request successful Fetching or updating a
resource
201 Created Resource successfully Creating a new product
created
204 No Content Request successful, no Deleting a resource
response body
Let's understand them through examples.
GET request:
GET /products Response:
200 OK { "data": [ { "id": 101, "name": "Wireless Headphones" } ] } POST request:
POST /products Response:
201 Created { "id": 102, "name": "Mechanical Keyboard" } DELETE request:
DELETE /products/102 Response:
204 No Content No response body is required.
Common error status codes
Status Code Meaning Typical Usage
400 Bad Request Invalid request Incorrect or malformed
input
401 Unauthorized Authentication required Missing or invalid
or invalid authentication
credentials
403 Forbidden Access denied User does not have
permission
404 Not Found Resource not found Requested product does
not exist
409 Conflict Resource conflict Duplicate or
conflicting operation
422 Unprocessable Request content cannot Validation failure
Content be processed
429 Too Many Requests Rate limit exceeded Too many requests in a
given period
500 Internal Server Unexpected server error Unhandled server-side
Error failure
Consistent error responses
Instead of returning different error structures from different
endpoints, we should follow a consistent format.
For example:
{ "error": { "message": "Product not found", "code": "PRODUCT_NOT_FOUND" } } For validation errors, we can provide additional details:
{ "error": { "message": "Validation failed", "code": "VALIDATION_ERROR", "details": [ { "field": "price", "message": "Price must be greater than zero" } ] } } This makes it easier for the frontend to understand errors and display
meaningful messages.
9. REST API Best Practices
Now that we understand the major components of REST API design, let's
look at some practices that help us build better APIs.
1. Provide interactive documentation
Documentation should explain:
- Available endpoints.
- HTTP methods.
- Required parameters.
- Request and response structures.
- Authentication requirements.
- Possible status codes.
Tools such as Swagger UI allow developers to explore and test APIs
interactively.
2. Make APIs intuitive and consistent
Follow the same naming conventions and response structures throughout
the application.
For example, avoid using different naming styles for similar resources.
Consistency makes APIs easier to understand and maintain.
3. Provide sensible defaults
Optional parameters should have predictable default values.
For example:
page = 1 limit = 10 sortOrder = desc This allows clients to use endpoints without specifying every parameter.
4. Avoid unnecessary abbreviations
Use meaningful names for endpoints and parameters.
Prefer:
GET /products?sortBy=createdAt Instead of:
GET /products?sb=ca Readable naming improves maintainability and reduces confusion.
5. Validate incoming requests
Never blindly trust data received from clients.
Validate:
- Required fields.
- Data types.
- Value ranges.
- Resource identifiers.
- Allowed query parameters.
This helps prevent invalid data from entering the application.
6. Use appropriate HTTP methods and status codes
Choose HTTP methods based on the intended operation and return status
codes that accurately describe the outcome.
7. Keep API responses predictable
Use consistent response structures for similar operations.
Clients should not have to understand a completely different response
format for every endpoint.
8. Protect your API
Use appropriate authentication, authorization, rate limiting, and input
validation.
These practices help protect both application resources and user data.
Conclusion
REST API design is not simply about creating endpoints and connecting a
frontend to a backend.
It is about establishing a consistent contract between clients and
servers.
By understanding resources, HTTP methods, idempotency, URL conventions,
pagination, filtering, sorting, and status codes, we can design APIs
that are easier to use and maintain.
The most important takeaway is that a good API should be predictable
for its consumers and consistent for its developers.
Once these principles become part of our design process, building larger
backend applications becomes much more manageable.
What's Next?
In the next blog, we'll explore Databases.
We'll understand how applications store, organize, retrieve, and manage
data, starting with database fundamentals and gradually exploring
different database types and their underlying concepts.
We'll continue building our backend knowledge from first principles, one
concept at a time.