REST API Development

Introduction to REST APIs

20 min Lesson 1 of 35

What is a REST API?

REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API (Application Programming Interface) is a way for different software applications to communicate with each other over the internet using standard HTTP methods.

Think of a REST API as a waiter in a restaurant. You (the client) tell the waiter (the API) what you want from the menu (the server's resources), and the waiter brings it to you. You don't need to know how the kitchen works - you just need to know how to order.

Note: REST APIs are the backbone of modern web applications. Services like Twitter, Facebook, Google Maps, and thousands of other platforms expose their functionality through REST APIs.

Why REST APIs Matter

REST APIs have become the standard for web services because they offer several key advantages:

  • Simplicity: Uses familiar HTTP methods (GET, POST, PUT, DELETE) that developers already understand
  • Scalability: Stateless architecture allows for easy horizontal scaling
  • Flexibility: Can return data in multiple formats (JSON, XML, HTML)
  • Platform Independence: Works with any programming language or platform that supports HTTP
  • Separation of Concerns: Frontend and backend can be developed independently

The Six Principles of REST

For an API to be considered RESTful, it must follow these architectural constraints:

1. Client-Server Architecture

The client and server are separate entities that communicate over a network. The client handles the user interface and user experience, while the server manages data storage and business logic. This separation allows both to evolve independently.

Client (React, Vue, Mobile App)
    ↓ HTTP Request
Server (Node.js, PHP, Python)
    ↓ HTTP Response
Client receives and displays data

2. Statelessness

Each request from client to server must contain all the information needed to understand and process the request. The server doesn't store any client context between requests. Each request is independent and self-contained.

Tip: Authentication tokens (like JWT) are included in every request header, allowing the server to identify the user without maintaining session state.

3. Cacheability

Responses must define themselves as cacheable or non-cacheable. If a response is cacheable, the client can reuse that response data for equivalent requests later, improving performance and reducing server load.

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600

{
  "id": 1,
  "name": "John Doe"
}

4. Uniform Interface

REST APIs follow a consistent and standardized approach to interacting with resources. This includes:

  • Resource Identification: Resources are identified by URIs (e.g., /users/123)
  • Resource Manipulation: Clients manipulate resources through representations (JSON, XML)
  • Self-Descriptive Messages: Each message includes enough information to describe how to process it
  • HATEOAS: Responses include links to related resources

5. Layered System

The client cannot tell whether it's connected directly to the end server or an intermediary. This allows for load balancers, proxies, and gateways to be added transparently.

6. Code on Demand (Optional)

Servers can temporarily extend client functionality by transferring executable code (like JavaScript). This is the only optional constraint.

HTTP Methods: The Verbs of REST

REST APIs use standard HTTP methods to perform operations on resources. Think of these as verbs that describe what action you want to perform:

Method Purpose Example
GET Retrieve data GET /users/123
POST Create new resource POST /users
PUT Update entire resource PUT /users/123
PATCH Update part of resource PATCH /users/123
DELETE Remove resource DELETE /users/123

HTTP Status Codes: The Response Language

Status codes tell the client whether their request was successful and what happened. They're grouped into five categories:

1xx - Informational

The request was received and is being processed. These are rarely seen in REST APIs.

2xx - Success

  • 200 OK: Request succeeded (GET, PUT, PATCH)
  • 201 Created: New resource created successfully (POST)
  • 204 No Content: Request succeeded but no content to return (DELETE)

3xx - Redirection

  • 301 Moved Permanently: Resource has permanently moved to a new URL
  • 304 Not Modified: Cached version is still valid

4xx - Client Errors

  • 400 Bad Request: Invalid request syntax or parameters
  • 401 Unauthorized: Authentication required or failed
  • 403 Forbidden: Authenticated but not authorized
  • 404 Not Found: Resource doesn't exist
  • 422 Unprocessable Entity: Validation failed
  • 429 Too Many Requests: Rate limit exceeded

5xx - Server Errors

  • 500 Internal Server Error: Generic server error
  • 503 Service Unavailable: Server temporarily unavailable
Warning: Never return a 200 OK status code when an error occurs. Always use the appropriate status code to help clients understand what happened.

The Request-Response Cycle

Understanding how data flows in a REST API is crucial. Here's what happens in a typical API request:

1. Client makes HTTP request
   → GET https://api.example.com/users/123
   → Headers: Authorization, Content-Type, etc.

2. Request travels through the internet
   → May pass through proxies, load balancers

3. Server receives request
   → Authenticates user
   → Validates request
   → Processes business logic

4. Server prepares response
   → Formats data (usually JSON)
   → Sets status code
   → Adds headers

5. Response sent back to client
   → Status: 200 OK
   → Body: {"id": 123, "name": "John"}

6. Client processes response
   → Updates UI
   → Caches if appropriate

Anatomy of a REST API Request

Let's break down what a typical API request looks like:

GET /api/v1/users/123 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
Accept: application/json
User-Agent: MyApp/1.0

Breaking it down:

  • Method: GET - we're retrieving data
  • Path: /api/v1/users/123 - the resource we want
  • Host: api.example.com - the server address
  • Authorization: Bearer token for authentication
  • Content-Type: Format of data we're sending
  • Accept: Format we want to receive

Anatomy of a REST API Response

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600
X-RateLimit-Remaining: 999

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2026-01-15T10:30:00Z",
  "links": {
    "self": "/api/v1/users/123",
    "posts": "/api/v1/users/123/posts"
  }
}

Response components:

  • Status Line: HTTP/1.1 200 OK
  • Headers: Metadata about the response
  • Body: The actual data (JSON object)
  • Links: Related resources (HATEOAS)

REST vs. Other Approaches

How does REST compare to other API architectures?

Aspect REST GraphQL SOAP
Protocol HTTP HTTP Multiple (HTTP, SMTP, etc.)
Data Format JSON, XML, HTML JSON XML only
Learning Curve Easy Moderate Steep
Flexibility High Very High Low
Tip: REST is perfect for most web applications and mobile apps. Consider GraphQL when you need flexible queries, and SOAP for enterprise systems requiring strict contracts and high security.

Real-World REST API Examples

Let's look at how popular services structure their REST APIs:

Twitter API - Get User Timeline

GET https://api.twitter.com/2/users/123/tweets
Authorization: Bearer YOUR_TOKEN

Response: 200 OK
{
  "data": [
    {
      "id": "1234567890",
      "text": "Hello world!",
      "created_at": "2026-02-14T10:00:00Z"
    }
  ],
  "meta": {
    "result_count": 1,
    "next_token": "xyz789"
  }
}

GitHub API - Create Repository

POST https://api.github.com/user/repos
Authorization: token YOUR_TOKEN
Content-Type: application/json

{
  "name": "my-new-repo",
  "description": "My awesome project",
  "private": false
}

Response: 201 Created
{
  "id": 123456,
  "name": "my-new-repo",
  "full_name": "username/my-new-repo",
  "html_url": "https://github.com/username/my-new-repo"
}
Exercise:

Think about an application you use daily (Instagram, Spotify, Gmail, etc.). Identify three different API endpoints they might have and what HTTP methods would be used:

  1. Example: GET /users/{id}/posts - retrieve user's posts
  2. Your turn: [Write your answer]
  3. Your turn: [Write your answer]
  4. Your turn: [Write your answer]

Key Takeaways

  • REST is an architectural style, not a protocol or standard
  • It uses standard HTTP methods (GET, POST, PUT, PATCH, DELETE)
  • Stateless design makes REST APIs scalable and maintainable
  • Status codes communicate what happened with the request
  • Resources are identified by URIs and manipulated through representations
  • REST APIs are platform-independent and language-agnostic

What's Next?

In the next lesson, we'll dive deeper into HTTP methods and status codes. You'll learn exactly when to use each method, how to handle different status codes, and best practices for structuring your API responses.

Remember: REST isn't about being perfect - it's about being practical and following conventions that make your API easy to understand and use. Focus on consistency and clarity over strict adherence to every REST principle.