REST API Explained With Examples: Complete Beginner Guide

REST APIs are one of the most common ways modern web applications communicate with backend systems.

When a frontend application loads user information, creates an order, updates a profile, or deletes a task, it may communicate with a backend through a REST-style API.

For beginners, REST can initially seem complicated because it involves terms such as resources, endpoints, HTTP methods, statelessness, JSON, status codes, authentication, and CRUD operations.

This guide explains REST APIs step by step with simple examples so that you can understand the concepts and start building your own APIs.

Simple Definition: A REST API is a web API designed according to principles of the REST architectural style, typically using HTTP methods to interact with resources.

What Does REST Stand For?

REST stands for Representational State Transfer.

REST was introduced as an architectural style for designing networked systems. It is not a programming language, framework, or protocol.

REST APIs commonly use the existing HTTP protocol to expose and manipulate resources.

What Is a REST API?

A REST API provides an interface that allows clients to communicate with server-side resources using HTTP.

The client can be:

  • A web browser
  • A React application
  • A mobile application
  • A desktop application
  • Another backend service
  • A command-line program

The server may contain:

  • Business logic
  • Databases
  • Authentication systems
  • File storage
  • External service integrations
Client
  |
  | HTTP Request
  v
REST API
  |
  v
Application Logic
  |
  v
Database
  |
  v
REST API
  |
  | HTTP Response
  v
Client
  

What Is a Resource in REST?

A resource is an important concept in REST.

A resource can represent something that the application manages, such as:

  • Users
  • Products
  • Orders
  • Students
  • Courses
  • Blog posts
  • Comments
  • Tasks

For example, in a student management system, students could be a resource.

An endpoint might be:

/api/students
  

A specific student could be identified by:

/api/students/101
  

REST API Endpoint Examples

Suppose we are building an online store.

Possible resource endpoints could be:

/api/products
/api/products/25
/api/users
/api/users/15
/api/orders
/api/orders/500
  

The URL identifies the resource being accessed.

HTTP Methods in REST APIs

REST APIs commonly use HTTP methods to indicate what operation the client wants to perform.

GET

GET is generally used to retrieve a resource.

GET /api/products
  

This could return a collection of products.

To retrieve one product:

GET /api/products/25
  

POST

POST is commonly used to submit data or create a resource.

POST /api/products
  

The request body might contain:

{
  "name": "Wireless Keyboard",
  "price": 1499
}
  

PUT

PUT is commonly used to replace the representation of a resource.

PUT /api/products/25
  

A complete replacement representation might look like:

{
  "name": "Mechanical Keyboard",
  "price": 2499
}
  

PATCH

PATCH is commonly used when only part of a resource needs to be modified.

PATCH /api/products/25
  

The client may send only the field that needs to change:

{
  "price": 2299
}
  

DELETE

DELETE is generally used to remove a resource.

DELETE /api/products/25
  

REST and CRUD Operations

REST APIs are frequently designed around CRUD operations.

CRUD stands for:

  • Create
  • Read
  • Update
  • Delete
CRUD HTTP Method Example
Create POST POST /api/users
Read GET GET /api/users/15
Update PUT/PATCH PATCH /api/users/15
Delete DELETE DELETE /api/users/15

REST API Example: Student Management System

Let's design a small REST API for students.

Get All Students

GET /api/students
  

Possible response:

[
  {
    "id": 1,
    "name": "Rahul",
    "course": "MCA"
  },
  {
    "id": 2,
    "name": "Anita",
    "course": "BCA"
  }
]
  

Get One Student

GET /api/students/1
  

Create a Student

POST /api/students
  

Request body:

{
  "name": "Aman",
  "course": "MCA"
}
  

Update a Student

PATCH /api/students/1
  

Request body:

{
  "course": "MCA 2nd Year"
}
  

Delete a Student

DELETE /api/students/1
  

What Is Statelessness in REST?

Statelessness is one of the important REST constraints.

In a stateless interaction, each request contains the information needed by the server to understand and process that request. The server does not rely on storing client session state between requests as part of the REST interaction.

For example, an authenticated API request might contain a token:

Authorization: Bearer YOUR_ACCESS_TOKEN
  

The server can use the supplied credential to identify and authorize the request according to its authentication system.

Why Is Statelessness Useful?

Stateless APIs can make horizontal scaling easier because requests do not necessarily need to be routed back to one specific application server to recover local session state.

However, real systems may use supporting infrastructure such as shared session stores, caches, databases, or gateways. Statelessness describes how the API interaction is designed, not a promise that no state exists anywhere in the entire application.

JSON in REST APIs

JSON is a common format for REST API requests and responses.

Example response:

{
  "id": 101,
  "name": "Adarsh",
  "role": "Developer",
  "skills": [
    "JavaScript",
    "Python",
    "SQL"
  ]
}
  

The server can generate this response and the frontend can parse it into application data.

HTTP Status Codes in REST APIs

REST APIs should use appropriate HTTP status codes to communicate the outcome of requests.

Status Common Meaning Typical Example
200 OK Successful GET or update response
201 Created New resource created
204 No Content Successful operation with no response body
400 Bad Request Invalid request data
401 Unauthorized Missing or invalid authentication
403 Forbidden Authenticated but not allowed
404 Not Found Resource does not exist
409 Conflict Request conflicts with current resource state
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Unexpected server-side failure

What Are REST API Headers?

HTTP headers provide metadata about requests and responses.

Common examples include:

Content-Type: application/json
Accept: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
  

Content-Type tells the server what format the request body uses.

Accept can indicate the response formats the client can process.

Authorization can carry authentication credentials when the API's security design uses them.

Path Parameters vs Query Parameters

Path Parameters

Path parameters identify a specific resource or part of a resource path.

GET /api/products/25
  

Here, 25 can identify the product.

Query Parameters

Query parameters are useful for filtering, searching, sorting, and pagination.

GET /api/products?category=laptop&page=2
  

REST API Pagination

Returning thousands or millions of records in a single API response can be inefficient.

APIs commonly provide pagination.

For example:

GET /api/products?page=1&limit=20
  

This could request a particular page containing a limited number of products.

The exact pagination design depends on the API.

REST API Filtering and Searching

Query parameters can also be used to filter resources.

GET /api/products?category=phones
GET /api/products?minPrice=10000&maxPrice=50000
GET /api/users?role=admin
  

A well-designed API should document supported query parameters and their expected values.

REST API Authentication

Many REST APIs require clients to authenticate before accessing protected resources.

Common approaches include:

  • API keys
  • Bearer tokens
  • OAuth-based flows
  • Session-based systems
  • Other token-based authentication mechanisms

A protected request could look like:

GET /api/profile

Authorization: Bearer YOUR_ACCESS_TOKEN
  

Authentication vs Authorization

These two concepts are related but different.

Authentication asks: "Who are you?"

Authorization asks: "What are you allowed to do?"

For example, a user might successfully authenticate but still receive a 403 Forbidden response when attempting an administrative operation without the required permission.

REST API Security Basics

REST APIs should be designed with security in mind from the beginning.

Use HTTPS

HTTPS protects API traffic in transit.

Validate Input

Never assume client-provided data is trustworthy.

Implement Authorization

Do not rely only on authentication. Verify that the authenticated identity has permission for each sensitive operation.

Protect Secrets

Do not hard-code passwords, API keys, private tokens, or database credentials in public source code.

Rate Limit Sensitive Endpoints

Rate limiting can help control abusive or excessive traffic and can be particularly important for authentication and resource-intensive endpoints.

Return Safe Errors

Errors should help legitimate clients understand the problem without revealing unnecessary internal details.

REST API Versioning

APIs can evolve over time.

When incompatible changes are introduced, existing applications may need protection from unexpected behavior.

A common versioning approach is:

/api/v1/users
/api/v2/users
  

Versioning strategies differ. Some APIs use URLs, while others use headers or other mechanisms.

What Are REST API Error Responses?

A useful API should provide structured error responses instead of returning confusing or inconsistent messages.

For example:

{
  "error": "validation_error",
  "message": "Email address is invalid",
  "field": "email"
}
  

The exact structure can vary, but consistency makes APIs easier to consume.

REST API Naming Best Practices

Resource-oriented naming can make an API easier to understand.

Prefer clear resource names:

/api/users
/api/products
/api/orders
  

rather than unnecessarily action-heavy URLs such as:

/api/getAllUsers
/api/createProduct
/api/deleteOrder
  

The HTTP method already communicates the intended operation in many REST designs.

REST API Example With Node.js and Express

Here is a simple learning example using Express.js.

const express = require("express");

const app = express();

app.use(express.json());

app.get("/api/users", (req, res) => {
  res.json([
    {
      id: 1,
      name: "Adarsh"
    },
    {
      id: 2,
      name: "Rahul"
    }
  ]);
});

app.post("/api/users", (req, res) => {
  const { name } = req.body;

  res.status(201).json({
    message: "User created",
    name
  });
});

app.listen(3000, () => {
  console.log("REST API running on port 3000");
});
  

This is only a learning example. A production API would also need appropriate validation, authentication, authorization, persistent storage, error handling, logging, security controls, and testing.

Calling a REST API From JavaScript

A frontend application can use the Fetch API to call a REST endpoint.

fetch("/api/users")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });
  

The frontend receives the JSON response and can use the returned data to update the interface.

Testing REST APIs

Before connecting an API to a frontend, developers can test it independently.

API testing tools can help you:

  • Send GET requests
  • Send POST requests
  • Modify request headers
  • Send JSON bodies
  • Test authentication
  • Inspect responses
  • Test error conditions
  • Save reusable requests

Postman, curl, and automated testing frameworks are commonly used for API testing.

Testing With curl

For example, a GET request can be sent from a terminal:

curl https://example.com/api/users
  

A POST request could look like:

curl -X POST https://example.com/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Adarsh"}'
  

The exact command depends on the API and operating system.

REST API Architecture Example

                 Client
                   |
                   v
              REST API
                   |
              +----+----+
              |         |
              v         v
          Controller   Auth
              |
              v
        Business Logic
              |
              v
           Database
  

A larger production application may contain additional layers such as API gateways, caches, queues, background workers, external services, observability systems, and multiple backend services.

REST API vs SOAP API

REST SOAP
Architectural style Protocol
Commonly uses HTTP Can operate over multiple underlying transports
Often uses JSON, but other formats are possible Traditionally associated with XML messaging
Common in web and mobile APIs Often used in enterprise systems requiring SOAP features and contracts

REST API vs GraphQL

REST GraphQL
Usually exposes resource-oriented endpoints Often exposes a schema and query language
Uses HTTP methods heavily Clients commonly describe the fields they need
Often straightforward for standard CRUD APIs Can be useful when clients need flexible data selection

Common REST API Mistakes

  1. Using unclear or inconsistent endpoint names.
  2. Ignoring HTTP status codes.
  3. Returning inconsistent response structures.
  4. Skipping input validation.
  5. Checking authentication but not authorization.
  6. Exposing secrets in source code.
  7. Returning sensitive internal information in error messages.
  8. Ignoring rate limiting for sensitive endpoints.
  9. Changing API behavior without a migration strategy.
  10. Building an API without documentation and tests.

How to Build Your First REST API

Beginners can follow this practical sequence:

  1. Learn HTTP fundamentals.
  2. Understand request and response structure.
  3. Learn JSON.
  4. Learn GET, POST, PUT, PATCH, and DELETE.
  5. Understand endpoints and parameters.
  6. Learn CRUD.
  7. Build a small API with a backend framework.
  8. Connect a database.
  9. Add validation.
  10. Add authentication and authorization.
  11. Test the API.
  12. Document the endpoints.
  13. Deploy the application.

Beginner REST API Project Ideas

1. Todo API

Create, read, update, and delete tasks.

2. Student API

Manage student profiles, courses, and academic information.

3. Blog API

Manage posts, categories, comments, and authors.

4. Expense Tracker API

Create endpoints for recording and analyzing personal expenses.

5. Library Management API

Manage books, members, borrowing, and returns.

6. Authentication API

Build a learning project around registration, login, authentication, and role-based authorization.

Frequently Asked Questions

```

What is a REST API in simple words?

A REST API is a way for applications to communicate over HTTP using resource-oriented interfaces and standard HTTP methods.

What does REST stand for?

REST stands for Representational State Transfer.

Is REST a programming language?

No. REST is an architectural style for designing networked applications.

What is the difference between API and REST API?

API is a broad concept describing a software interface. REST API refers specifically to an API designed according to principles associated with REST.

What are the main REST API methods?

GET, POST, PUT, PATCH, and DELETE are commonly used in REST APIs.

What is CRUD in REST API?

CRUD means Create, Read, Update, and Delete. REST APIs commonly map these operations to HTTP methods.

Does every REST API use JSON?

No. REST does not require JSON. JSON is simply a very common representation format for modern web APIs.

What is a REST API endpoint?

An endpoint is a specific URL through which a client accesses a resource or operation exposed by an API.

Is REST API secure?

A REST API can be secure when it is correctly designed and implemented. Security requires appropriate authentication, authorization, transport protection, input validation, secret management, logging, and other controls.

Can beginners build REST APIs?

Yes. Beginners can start with a small CRUD API and gradually add databases, authentication, validation, testing, and deployment.

```

Final Thoughts

REST APIs provide a practical way for different software components to communicate over HTTP.

The most important concepts to understand are resources, endpoints, HTTP methods, requests, responses, JSON, status codes, CRUD, statelessness, authentication, authorization, and API security.

You do not need to memorize every REST concept before writing your first API. Build a small project, test each endpoint, inspect the requests and responses, and gradually add production-level features.

CodeWithAV REST API Learning Path:

HTTP → JSON → Resources → Endpoints → GET/POST → PUT/PATCH/DELETE → CRUD → Authentication → Authorization → Database → Testing → Documentation → Deployment.

Related Articles on CodeWithAV

What Is an API? Complete Beginner Guide

What Is JSON?

HTTP vs HTTPS Explained

HTTP Status Codes Every Developer Should Know

What Is Cloud Computing?

Explore More Web Development Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.