If you have ever used a weather app, logged in with Google, or made an online payment, you have interacted with a REST API — you just did not see it. REST APIs are the invisible backbone of modern software, enabling applications to communicate with each other over the internet. Understanding REST APIs is essential knowledge for every developer, whether you are building frontends, backends, mobile apps, or integrating third-party services.
This guide explains what REST APIs are from the ground up — no prior API knowledge required. By the end, you will understand how APIs work, how to read and write API requests, and how to design your own RESTful services.
What Is an API?
An API (Application Programming Interface) is a set of rules that allows one piece of software to talk to another. It defines what requests you can make, what data you need to send, and what response you will get back.
Real-world analogy: Think of a restaurant. You (the client) do not go into the kitchen to cook your food. Instead, you tell the waiter (the API) what you want from the menu (the request). The waiter takes your order to the kitchen (the server), and brings back your food (the response). The API is the waiter — the middleman that lets you interact with the kitchen without knowing how the food is actually prepared.
In software: your mobile app (client) does not directly access the database. Instead, it sends a request to the API, which talks to the database and returns the data in a structured format.
What Is a REST API?
REST stands for Representational State Transfer. It is an architectural style (a set of design principles) for building web APIs. A REST API is an API that follows these REST principles — using standard HTTP methods, resource-based URLs, and stateless communication.
REST was defined by Roy Fielding in his 2000 doctoral dissertation. It became the dominant web API architecture because it leverages the existing HTTP protocol that powers the web — no special software, protocols, or libraries needed. Any device that can make HTTP requests can use a REST API.
A REST API exposes "resources" (data entities like users, products, orders) at specific URLs, and you interact with them using standard HTTP methods (GET to read, POST to create, PUT to update, DELETE to remove).
How REST APIs Work
Every REST API interaction follows this pattern:
CLIENT (Browser/App)
Sends HTTP request to a URL
REST API SERVER
Processes request, interacts with database
RESPONSE
Returns JSON data + HTTP status code
Example: Getting a user's profile
// Request
GET https://api.example.com/users/123
Headers: { "Authorization": "Bearer eyJhbG..." }
// Response (200 OK)
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"role": "admin",
"createdAt": "2024-01-15T10:30:00Z"
}HTTP Methods in REST APIs
REST APIs use HTTP methods (also called verbs) to indicate what action to perform on a resource. Each method has a specific purpose:
GET /users/123
Response: { "id": 123, "name": "Alice" }
Use case: Fetching a user profile, listing products, getting search results
POST /users
Body: { "name": "Bob", "email": "bob@example.com" }Response: { "id": 124, "name": "Bob" } (201 Created)
Use case: Creating a new account, submitting a form, uploading a file
PUT /users/123
Body: { "name": "Alice Smith", "email": "alice@new.com" }Response: { "id": 123, "name": "Alice Smith" } (200 OK)
Use case: Updating a user profile completely, replacing a document
PATCH /users/123
Body: { "name": "Alice Smith" }Response: { "id": 123, "name": "Alice Smith" } (200 OK)
Use case: Changing just the name, updating just the status field
DELETE /users/123
Response: (204 No Content)
Use case: Deleting an account, removing a product, canceling an order
HTTP Status Codes
Status codes tell the client what happened with their request:
| Code | Name | Meaning | When used |
|---|---|---|---|
| 200 | OK | Request succeeded | GET, PUT, PATCH successful |
| 201 | Created | Resource created successfully | POST successful |
| 204 | No Content | Success, nothing to return | DELETE successful |
| 400 | Bad Request | Invalid input from client | Missing required fields, wrong format |
| 401 | Unauthorized | Authentication required | No token or invalid token |
| 403 | Forbidden | No permission | Valid token but insufficient role |
| 404 | Not Found | Resource does not exist | Wrong URL or deleted resource |
| 409 | Conflict | Resource conflict | Duplicate email, username taken |
| 422 | Unprocessable | Validation failed | Invalid email format, password too short |
| 500 | Server Error | Something broke on server | Bug in code, database down |
The 6 REST Constraints
For an API to be truly "RESTful," it must follow these architectural constraints:
1. Client-Server
The client (frontend) and server (backend) are separate and independent. The client handles the UI; the server handles data storage and business logic. They communicate only through the API. This separation means you can change the frontend without touching the backend, and vice versa.
2. Stateless
Every request must contain all the information the server needs to process it. The server does not remember previous requests — each request is independent. Authentication tokens, user context, and parameters must be included in every request. This makes scaling easy because any server can handle any request.
3. Cacheable
Responses should indicate whether they can be cached by the client. Caching reduces server load and improves performance. For example, a product catalog that changes once a day can be cached — the client does not need to fetch it on every page view.
4. Uniform Interface
All resources are accessed through a consistent, predictable interface. Resources are identified by URLs (/users/123), manipulated with HTTP methods (GET, POST, PUT, DELETE), and responses include enough information for the client to understand and modify the resource.
5. Layered System
The client does not need to know if it is talking directly to the server or to an intermediary (like a load balancer, cache, or API gateway). Each layer only sees the layer it directly interacts with. This enables infrastructure flexibility without changing the API.
6. Code on Demand (optional)
Servers can optionally send executable code to clients (like JavaScript). This is the only optional constraint and is rarely discussed in the context of REST APIs. Most REST APIs just send data, not code.
REST API URL Design Best Practices
Well-designed URLs make your API intuitive and self-documenting. REST URLs should represent resources (things), not actions:
✅ Good (Resource-based)
GET /users GET /users/123 POST /users PUT /users/123 DELETE /users/123 GET /users/123/orders GET /products?category=electronics GET /api/v2/users
❌ Bad (Action-based)
GET /getUsers POST /createUser POST /deleteUser/123 GET /fetchAllProducts POST /api/v1/updateUserEmail GET /getAllOrdersForUser
- Use nouns, not verbs: The HTTP method is the verb. The URL is the noun (resource).
- Use plural names: /users (not /user), /products (not /product).
- Use lowercase and hyphens: /user-profiles (not /UserProfiles or /user_profiles).
- Version your API: /api/v1/users — allows backward-compatible changes.
- Nest for relationships: /users/123/orders — orders belonging to user 123.
REST API Request Structure
Every REST API request consists of several components. Understanding each part helps you read API documentation and debug issues effectively:
POST https://api.example.com/v1/users?notify=true
Headers:
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Accept: application/json
Body:
{
"name": "Alice",
"email": "alice@example.com",
"role": "editor"
}URL (Endpoint)
https://api.example.com/v1/usersThe address of the resource. Includes the base URL, API version, and resource path.
HTTP Method
POSTThe action to perform — GET (read), POST (create), PUT (update), DELETE (remove).
Path Parameters
/users/123 → 123 is the path paramDynamic segments in the URL that identify a specific resource. Defined as :id in route patterns.
Query Parameters
?notify=true&page=2&limit=20Optional parameters appended after ? for filtering, sorting, pagination, or flags. Not part of the resource identity.
Headers
Authorization, Content-Type, AcceptMetadata about the request — authentication tokens, content format, caching directives, and custom headers.
Request Body
{ "name": "Alice", "email": "..." }The data payload sent with POST, PUT, and PATCH requests. Usually JSON. GET and DELETE typically have no body.
REST API Authentication Methods
Most APIs require authentication to identify who is making the request and what permissions they have. Here are the four most common authentication methods used with REST APIs:
API Keys
A simple token (long random string) sent with each request, usually in a header or query parameter. Easy to implement but offers no user-level identity — just identifies the application. Common for public APIs with rate limiting (Google Maps, OpenWeather).
GET /api/weather?city=London&apiKey=abc123def456
JWT (Bearer Token) Authentication
After login, the server issues a signed JWT token. The client sends it in the Authorization header with every request. The server verifies the signature without a database lookup. Ideal for SPAs, mobile apps, and microservices.
GET /api/profile Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
OAuth 2.0
A delegation protocol that lets users grant third-party apps limited access to their accounts without sharing passwords. Used for "Login with Google/GitHub" flows and third-party API integrations. More complex but provides granular permission scopes.
GET /api/user/repos Authorization: Bearer github_pat_abc123... (OAuth access token)
Session Cookies
Traditional server-side sessions where the server stores user state and returns a session ID cookie. The browser sends the cookie automatically. Best for server-rendered web applications where the frontend and backend are on the same domain.
GET /api/dashboard Cookie: session_id=abc123def456 (sent automatically by browser)
For most modern applications: use JWT for APIs consumed by mobile/SPA clients, OAuth 2.0 for third-party integrations, and API keys for simple server-to-server communication. See ourJWT vs Session Authenticationguide for a deeper comparison.
REST vs SOAP vs GraphQL
| Feature | REST | SOAP | GraphQL |
|---|---|---|---|
| Data format | JSON (usually) | XML only | JSON |
| Complexity | Simple | Complex | Medium |
| Endpoints | Multiple (per resource) | Single (WSDL) | Single (/graphql) |
| Over-fetching | Possible | Possible | Solved (client specifies) |
| Caching | Easy (HTTP caching) | Difficult | Complex |
| Learning curve | Low | High | Medium |
| Real-time | Polling / WebSocket | Not standard | Subscriptions built-in |
| Best for | Most web/mobile APIs | Enterprise/banking | Complex data needs |
| Adoption (2026) | ~80% of APIs | ~5% (legacy) | ~15% (growing) |
Building a Simple REST API (Node.js + Express)
Here is a complete, working REST API for a "users" resource in under 50 lines:
const express = require("express")
const app = express()
app.use(express.json())
// In-memory "database"
let users = [
{ id: 1, name: "Alice", email: "alice@example.com" },
{ id: 2, name: "Bob", email: "bob@example.com" },
]
// GET all users
app.get("/api/users", (req, res) => {
res.json(users)
})
// GET single user
app.get("/api/users/:id", (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id))
if (!user) return res.status(404).json({ error: "User not found" })
res.json(user)
})
// CREATE user
app.post("/api/users", (req, res) => {
const { name, email } = req.body
if (!name || !email) return res.status(400).json({ error: "Name and email required" })
const user = { id: users.length + 1, name, email }
users.push(user)
res.status(201).json(user)
})
// UPDATE user
app.put("/api/users/:id", (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id))
if (!user) return res.status(404).json({ error: "User not found" })
user.name = req.body.name || user.name
user.email = req.body.email || user.email
res.json(user)
})
// DELETE user
app.delete("/api/users/:id", (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id))
res.status(204).send()
})
app.listen(3000, () => console.log("API running on port 3000"))This demonstrates all five CRUD operations (Create, Read, Update, Delete) mapped to HTTP methods. In production, you would add authentication, input validation, error handling, and connect to a real database — but the URL and method patterns remain the same.
REST API Best Practices
Return 201 for creation, 404 for not found, 400 for validation errors. Don't return 200 for everything — status codes are how clients know what happened.
Never return thousands of records in one response. Use ?page=2&limit=20 or cursor-based pagination for large collections.
Let clients filter results: /products?category=electronics&sort=price&order=asc. Reduces over-fetching without needing GraphQL.
Never trust client data. Validate types, lengths, formats, and required fields. Return clear 400/422 errors with specific messages.
Always return errors in the same shape: { error: { code: 'VALIDATION_ERROR', message: '...', details: [...] } }. Clients should not have to guess.
Use /api/v1/... so you can make breaking changes in v2 without breaking existing clients.
Never serve API endpoints over HTTP. Authentication tokens and user data must be encrypted in transit.
Protect against abuse and DDoS. Return 429 Too Many Requests with a Retry-After header.
Common REST API Mistakes
⚠️ Using GET for actions that modify data
GET should only read data — never use GET /deleteUser/123. Use DELETE /users/123 instead. GET requests can be cached and retried by browsers.
⚠️ Using verbs in URLs instead of nouns
/api/createUser and /api/getUsers are not RESTful. Use /api/users with different HTTP methods (POST to create, GET to list).
⚠️ Returning 200 for errors
Don't return { status: 200, error: 'User not found' }. Use proper HTTP status codes — 404 for not found, 401 for unauthorized. Clients rely on status codes for error handling.
⚠️ Not validating input
Trusting client data leads to crashes, injection attacks, and data corruption. Always validate on the server, even if the frontend also validates.
⚠️ Returning too much data (no pagination)
GET /users returning 10,000 users crashes mobile apps and wastes bandwidth. Always paginate list endpoints.
⚠️ Inconsistent response format
One endpoint returns { user: {...} }, another returns { data: {...} }. Pick one format and stick with it across all endpoints.
Real-World REST API Examples
These popular APIs follow REST principles and are great examples to learn from:
GitHub API
api.github.comOne of the best-documented REST APIs. Covers repositories, issues, pull requests, and user profiles. Supports pagination, filtering, and authentication via tokens.
Stripe API
api.stripe.comPayment processing API used by millions. Excellent error handling, versioning (date-based), and idempotency support for safe retries.
Twitter/X API
api.twitter.comSocial media API for tweets, users, and timelines. Demonstrates rate limiting, cursor-based pagination, and OAuth authentication.
OpenWeather API
api.openweathermap.orgSimple REST API perfect for beginners. Query by city name or coordinates, returns JSON weather data. Free tier available.
Frequently Asked Questions
What is a REST API in simple terms?
What is the difference between an API and a REST API?
Why are REST APIs so popular?
Is REST API still used in 2026?
What data format do REST APIs use?
Do I need to learn REST API as a frontend developer?
What is the difference between REST and GraphQL?
Related Tools & Articles
Conclusion
A REST API is a standardized way for applications to communicate over HTTP using resources (URLs), HTTP methods (GET, POST, PUT, DELETE), and status codes. It is the foundation of modern web development — powering everything from social media apps to payment systems to cloud infrastructure.
The key concepts to remember: resources are nouns (URLs), actions are verbs (HTTP methods), requests are stateless (each contains all needed information), and responses include proper status codes with structured JSON data. Master these fundamentals and you can work with any REST API — whether consuming third-party services or building your own.
Start by exploring real APIs (GitHub, OpenWeather) with tools like Postman or curl. Then build your own with Node.js + Express. The patterns you learn will apply to every API you encounter throughout your career.
