REST API Tutorial for Beginners: Methods, Endpoints, JSON, CRUD and Examples

REST API Tutorial for Beginners: Methods, Endpoints, JSON, CRUD and Examples

Modern applications rarely work as a single piece of software.

A website may have a frontend, backend, database, authentication system, payment provider, cloud service and several other services working together.

One of the most common ways these components communicate is through an API.

A popular style for designing web APIs is REST.

In this beginner-friendly tutorial, you will learn:

  • What REST API means
  • How REST APIs work
  • What an endpoint is
  • HTTP methods
  • CRUD operations
  • JSON requests and responses
  • Status codes
  • Headers
  • Parameters
  • Authentication
  • API testing
  • REST API security
  • How to build a simple REST API
Beginner Tip: Before learning REST APIs, understand basic HTTP concepts such as requests, responses, URLs, headers and status codes.

What Is REST?

REST stands for Representational State Transfer.

REST is an architectural style used to design networked applications and web APIs.

REST APIs commonly use standard HTTP methods and resource-oriented URLs.

A simple REST API might look like:

GET    /users
GET    /users/10
POST   /users
PATCH  /users/10
DELETE /users/10

Here, users represents a resource and different HTTP methods represent different operations.

What Is a REST API?

A REST API is an API designed around REST principles that allows software clients to communicate with resources over a network, commonly using HTTP.

For example, a mobile application may request a list of products:

GET /api/products

The server might return:

{
  "products": [
    {
      "id": 1,
      "name": "Laptop"
    },
    {
      "id": 2,
      "name": "Keyboard"
    }
  ]
}

The application can then display the information to the user.

REST API Architecture

A common web application architecture looks like this:

Frontend
↓
REST API
↓
Backend Application
↓
Database

The frontend does not necessarily communicate directly with the database.

Instead, it sends requests to the backend API, which applies business logic and interacts with the database.

How Does a REST API Work?

The basic process is:

  1. The client creates a request.
  2. The request is sent to an API endpoint.
  3. The server receives and validates the request.
  4. The backend performs the required operation.
  5. The server creates a response.
  6. The response is sent back to the client.
  7. The client processes and displays the result.

For example:

Browser
↓
GET /api/products
↓
Backend
↓
Database
↓
JSON Response
↓
Browser

What Is a Resource in REST?

A resource is an entity that an API exposes.

Examples include:

  • Users
  • Products
  • Orders
  • Students
  • Courses
  • Payments
  • Posts
  • Comments

A REST API usually represents resources using URLs.

For example:

/users
/products
/orders
/courses
/posts

What Is an Endpoint?

An endpoint is a specific API URL through which a client can access a resource or perform a supported operation.

Example:

https://example.com/api/users

Another endpoint could be:

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

The first may represent a collection of users, while the second may represent one user.

REST API HTTP Methods

The HTTP method tells the server what kind of operation the client is requesting.

The most commonly used methods in CRUD-style REST APIs are:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

GET

GET is commonly used to retrieve data.

Example:

GET /api/products

Get one product:

GET /api/products/101

GET requests are generally used for retrieving information rather than changing server state.

POST

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

Example:

POST /api/products

Request body:

{
  "name": "Laptop",
  "price": 55000
}

PUT

PUT is commonly used when a client wants to replace or update a resource representation.

Example:

PUT /api/products/101

Example body:

{
  "name": "Gaming Laptop",
  "price": 75000
}

The exact update behavior depends on the API implementation.

PATCH

PATCH is commonly used for partial modifications.

Example:

PATCH /api/products/101

Request:

{
  "price": 70000
}

This example changes only the price field rather than sending the complete resource.

DELETE

DELETE is commonly used to remove a resource.

Example:

DELETE /api/products/101

Delete operations should require proper authentication and authorization.

CRUD and REST APIs

CRUD stands for:

  • Create
  • Read
  • Update
  • Delete

A basic REST API often maps these operations to HTTP methods.

CRUD HTTP Method Example
Create POST POST /products
Read GET GET /products/101
Update PUT / PATCH PATCH /products/101
Delete DELETE DELETE /products/101

What Is JSON?

JSON stands for JavaScript Object Notation.

JSON is commonly used to represent structured data exchanged between applications.

Example:

{
  "id": 101,
  "name": "Adarsh",
  "active": true,
  "skills": [
    "Python",
    "JavaScript"
  ]
}

JSON supports common data types such as strings, numbers, booleans, arrays, objects and null values.

Request vs Response

A REST API interaction usually involves two sides.

Request

The client sends information to the server.

Response

The server returns the result.

A simple request could look like:

GET /api/users/101

The response might be:

{
  "id": 101,
  "name": "Adarsh",
  "role": "developer"
}

What Are HTTP Headers?

HTTP headers carry metadata about a request or response.

Common examples include:

  • Content-Type
  • Accept
  • Authorization
  • User-Agent
  • Cache-Control

Example:

Content-Type: application/json

This indicates that the message body uses JSON.

What Is Content-Type?

The Content-Type header tells the receiving side what type of content is being sent.

Common API examples include:

Content-Type: application/json

Other media types are possible depending on the API.

What Is Accept?

The Accept header can indicate which response media types the client can handle.

Example:

Accept: application/json

What Are HTTP Status Codes?

Status codes tell the client the general outcome of a request.

Status Meaning
200 Successful request
201 Resource created
204 Successful response with no response body
400 Bad request
401 Authentication required or unsuccessful
403 Request understood but access is forbidden
404 Resource not found
409 Request conflicts with the current state
422 Request data cannot be processed by the server
429 Too many requests
500 Internal server error

What Are Query Parameters?

Query parameters are values included after a ? in a URL.

Example:

/products?category=laptops&limit=10

Here:

  • category = laptops
  • limit = 10

Query parameters are commonly used for filtering, searching, pagination and sorting.

What Are Path Parameters?

Path parameters are values included directly in the URL path.

Example:

/users/101

Here 101 can represent a specific user.

Query Parameter vs Path Parameter

Path Parameter Query Parameter
/users/101 /users?id=101
Often identifies a specific resource Often filters or modifies a collection request
Part of the resource path Appears after the question mark

What Is Request Body?

A request body contains data sent by the client to the server.

It is commonly used with POST, PUT and PATCH requests.

Example:

{
  "name": "Laptop",
  "price": 65000,
  "stock": 15
}

What Is REST API Authentication?

Some APIs are public, while others require clients to authenticate.

Authentication determines the identity associated with a request.

Authorization determines whether that identity is allowed to perform the requested operation.

Common authentication approaches include:

  • API keys
  • Bearer tokens
  • Session cookies
  • OAuth-based systems

Bearer Token Example

A token may be sent in an Authorization header:

Authorization: Bearer YOUR_TOKEN

The exact format depends on the API.

REST API Security

API security should be designed into the application from the beginning.

Important areas include:

  • Authentication
  • Authorization
  • Input validation
  • Output control
  • Rate limiting
  • HTTPS
  • Secure secret storage
  • Logging
  • Monitoring
  • Access control

Authentication Is Not Authorization

Consider a school management application.

A student may successfully log in.

That does not mean the student should be allowed to:

  • Delete another student's account
  • Modify administrator settings
  • Change exam results
  • View private administrative information

The API must enforce permissions on the server.

Validate API Input

Never assume that the client sends correct data.

For example, an API expecting:

{
  "age": 25
}

should not blindly trust that the value is a valid age.

Server-side validation should check:

  • Type
  • Format
  • Required fields
  • Length
  • Allowed values
  • Business rules

Use HTTPS

REST APIs that handle private information, credentials or authenticated sessions should normally be served over HTTPS.

HTTPS helps protect data while it is transmitted between client and server.

Protect API Credentials

Never put private API keys directly into public source code.

A bad example is:

const API_KEY = "my-secret-key";

A better architecture is to keep secrets on the server and load them from secure configuration or a secrets-management system.

What Is API Rate Limiting?

Rate limiting controls the amount of traffic a client can send.

For example, an API may define a limit such as:

100 requests per minute

Rate limiting can help protect APIs against excessive traffic, accidental overload and certain forms of abuse.

What Is API Pagination?

Returning thousands of records in one response is often inefficient.

APIs can use pagination to return smaller groups of records.

Example:

GET /products?page=1&limit=20

This could request the first page with 20 products.

What Is API Filtering?

Filtering allows clients to request only records matching specific criteria.

Example:

GET /products?category=laptop

The server can return only products matching the requested category.

What Is API Sorting?

Sorting can allow clients to control the order of returned resources.

For example:

GET /products?sort=price

The exact supported syntax depends on the API design.

REST API Versioning

APIs evolve over time.

One possible versioning strategy is:

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

Versioning can help manage changes while supporting older clients.

REST API Error Handling

A good API should return meaningful errors without exposing sensitive internal details.

For example:

{
  "error": {
    "code": "INVALID_EMAIL",
    "message": "Please provide a valid email address."
  }
}

Avoid returning sensitive information such as passwords, private keys, internal stack traces or database credentials.

How to Test a REST API

There are several ways to test APIs.

1. Postman

Postman provides a graphical interface for sending requests and examining API responses.

2. cURL

cURL can send HTTP requests from the command line.

Example:

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

3. Browser Developer Tools

Web browsers provide network tools for inspecting requests made by websites.

cURL GET Example

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

cURL POST Example

A JSON request can look like:

curl -X POST https://example.com/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Laptop","price":65000}'

Use these kinds of commands only with APIs and systems where you are authorized to send requests.

JavaScript REST API Example

JavaScript applications can use fetch() to communicate with APIs.

fetch("https://example.com/api/products")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

JavaScript POST Example

fetch("https://example.com/api/products", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Laptop",
    price: 65000
  })
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Production code should also handle non-success status codes and network failures appropriately.

Python REST API Example

Python applications can use HTTP libraries to communicate with REST APIs.

import requests

response = requests.get(
    "https://example.com/api/products",
    timeout=10
)

response.raise_for_status()

data = response.json()

print(data)

The timeout and error-handling approach should be adapted to your specific application.

Build a Simple REST API

One of the best ways to understand REST is to build a small project.

Let's imagine a Task Management API.

Resource

tasks

Endpoints

GET    /api/tasks
GET    /api/tasks/1
POST   /api/tasks
PATCH  /api/tasks/1
DELETE /api/tasks/1

Task Object

{
  "id": 1,
  "title": "Learn REST APIs",
  "completed": false,
  "priority": "high"
}

Building the API With Node.js

A common beginner stack is:

  • Node.js
  • Express.js
  • Database
  • REST endpoints

A minimal Express application might look like:

const express = require("express");

const app = express();

app.use(express.json());

app.get("/api/tasks", (req, res) => {
  res.json([
    {
      id: 1,
      title: "Learn REST APIs",
      completed: false
    }
  ]);
});

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

This is only a simple demonstration. A real application needs persistence, validation, error handling, authentication, authorization and other production controls.

Building the API With Python

Python developers can use frameworks such as FastAPI or Flask.

A basic FastAPI example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/api/tasks")
def get_tasks():
    return [
        {
            "id": 1,
            "title": "Learn REST APIs",
            "completed": False
        }
    ]

Again, this is a learning example rather than a complete production API.

Database and REST API

A REST backend commonly communicates with a database.

For example:

Client
↓
REST API
↓
Business Logic
↓
Database

Suppose the client sends:

GET /api/students/101

The backend may:

  1. Validate the request.
  2. Check authorization.
  3. Query the database.
  4. Transform the result.
  5. Return JSON.

REST API and Authentication Example

A protected endpoint might look like:

GET /api/profile

The client could send an authorization header:

Authorization: Bearer YOUR_ACCESS_TOKEN

The server should verify the credential and determine whether the user has permission to access the requested resource.

REST API and JWT

JWT stands for JSON Web Token.

JWTs are commonly used in some API authentication architectures to represent claims that can be verified by the server.

A simplified flow is:

Login
↓
Server Verifies Credentials
↓
Access Token
↓
Client Sends Token
↓
Protected API

Authentication systems need careful implementation, including token lifetime, storage, revocation strategy and authorization rules.

REST API Documentation

Good API documentation helps developers understand how to use the service.

Documentation should explain:

  • Base URL
  • Endpoints
  • HTTP methods
  • Parameters
  • Request body
  • Authentication
  • Response format
  • Status codes
  • Errors
  • Examples

OpenAPI

OpenAPI is a standard way to describe HTTP APIs in a machine-readable format.

An OpenAPI document can describe:

  • Paths
  • Methods
  • Parameters
  • Request bodies
  • Responses
  • Authentication schemes

This information can then be used by tools to generate documentation and support development workflows.

REST API Best Practices

1. Use Clear Resource Names

Prefer readable resource-oriented paths.

Example:

/users
/products
/orders

2. Use HTTP Methods Consistently

Choose methods according to the operation the endpoint represents.

3. Return Appropriate Status Codes

Use meaningful status codes so clients can understand the result.

4. Validate Input

Validate data on the server.

5. Protect Sensitive Endpoints

Apply authentication and authorization where required.

6. Use HTTPS

Protect network communication for sensitive APIs.

7. Avoid Exposing Internal Errors

Return useful client-facing error information without leaking internal implementation details.

8. Document Your API

Good documentation makes integration easier.

9. Add Rate Limits

Protect public and sensitive endpoints from excessive traffic.

10. Log Important Events

Logging can help troubleshoot problems and investigate suspicious activity.

REST API Common Mistakes

Using GET to Change Data

GET should generally be used to retrieve data rather than performing destructive changes.

Putting Secrets in URLs

Avoid placing sensitive credentials directly in URLs because URLs can be logged or exposed in unintended places.

No Authorization Checks

Always verify that the authenticated user is allowed to access or change the requested resource.

No Validation

Never trust input simply because it comes from your own frontend.

Huge Responses

Return only the data necessary for the client and consider pagination for large collections.

Poor Error Handling

Clients need consistent and understandable error responses.

REST API vs SOAP

REST and SOAP are different approaches to building networked services.

REST SOAP
Architectural style Messaging protocol
Commonly uses HTTP Can use HTTP and other transports
Often uses JSON Commonly associated with XML
Often lightweight More formal messaging model

Both approaches can be useful depending on the system and requirements.

REST API vs GraphQL

REST and GraphQL solve related API communication problems in different ways.

A REST API may expose endpoints such as:

GET /users/101
GET /users/101/orders

GraphQL commonly exposes a query interface through which clients request the fields they need.

Neither approach is automatically better for every application.

REST API vs Webhook

With a REST API, a client commonly requests information or asks a server to perform an operation.

A webhook is commonly used for event notifications, where one service sends information to another service when a specified event occurs.

Example:

Payment Completed
↓
Webhook
↓
Your Server

REST API Project Ideas

Once you understand the basics, build one of these projects:

  • Todo REST API
  • Student management API
  • Book library API
  • Expense tracker API
  • Blog API
  • Product management API
  • Movie API client
  • Weather API application
  • Job listing API
  • AI application API

Beginner REST API Project Structure

A simple project might contain:

project/
├── routes/
├── controllers/
├── models/
├── middleware/
├── services/
├── config/
├── tests/
└── server.js

The exact folder structure depends on your language and framework.

REST API Testing Checklist

Before considering an API complete, test:

  • Valid requests
  • Invalid requests
  • Missing fields
  • Invalid IDs
  • Unauthorized requests
  • Forbidden requests
  • Large inputs
  • Rate-limit behavior
  • Server errors
  • Database failures

REST API Learning Roadmap

HTTP Basics
↓
Requests & Responses
↓
JSON
↓
HTTP Methods
↓
Endpoints
↓
CRUD
↓
Authentication
↓
Database Integration
↓
API Testing
↓
API Security
↓
Documentation
↓
Build Your Own API

What Should You Learn After REST APIs?

Once you understand REST APIs, continue with:

  • Databases
  • Authentication
  • JWT
  • OAuth
  • API security
  • Testing
  • OpenAPI
  • Docker
  • Cloud deployment
  • Microservices

Final Thoughts

REST APIs are one of the most useful concepts for anyone learning modern web development.

They provide a structured way for applications to communicate with backend services.

If you understand:

Resources → Endpoints → HTTP Methods → JSON → Status Codes → Authentication

you already have a strong foundation for building and consuming web APIs.

The best way to learn REST is to stop reading after the basics and build something.

Create a small API, connect it to a frontend, store data in a database, add authentication, test the endpoints and deploy the application.

That practical experience will teach you far more than memorizing a list of HTTP methods.

CodeWithAV Tip: Build a Todo API first. Implement GET, POST, PATCH and DELETE. Then connect it to a React or JavaScript frontend. Once that works, add authentication and a database.

Frequently Asked Questions

What is a REST API?

A REST API is an API designed around REST principles and commonly uses HTTP to expose resources and operations.

What does REST stand for?

REST stands for Representational State Transfer.

What are the main REST API methods?

GET, POST, PUT, PATCH and DELETE are among the most commonly used methods in REST APIs.

What is CRUD?

CRUD stands for Create, Read, Update and Delete.

What is an API endpoint?

An endpoint is a specific URL or route through which an API exposes a resource or operation.

Why is JSON commonly used in REST APIs?

JSON provides a convenient way to represent structured data and is widely supported by modern programming languages and web technologies.

What is the difference between PUT and PATCH?

PUT is commonly used for replacing or updating a resource representation, while PATCH is commonly used for partial modifications.

What is the difference between 401 and 403?

401 generally indicates that authentication is required or was unsuccessful, while 403 generally indicates that the server understood the request but the client is not permitted to access the requested resource.

Can I build REST APIs with Python?

Yes. Frameworks such as FastAPI and Flask can be used to build REST-style APIs.

Can I build REST APIs with Node.js?

Yes. Node.js frameworks such as Express can be used to build REST APIs.

Are REST APIs secure automatically?

No. Security depends on proper authentication, authorization, validation, HTTPS, secret management, rate limiting, logging and other application controls.

Which tool can I use to test a REST API?

Postman, cURL and browser developer tools are common options for API testing and troubleshooting.

Related CodeWithAV Articles

What Is an API? Complete Beginner Guide

What Is JSON?

HTTP vs HTTPS Explained

Python Roadmap for Beginners

Web Development Roadmap for Beginners

About CodeWithAV: CodeWithAV publishes practical technology, AI, programming, cybersecurity, education, career and digital-tool resources for students, developers and professionals.
Adarsh verma

Adarsh verma

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