# REST APIs

An API, or application programming interface, is a set of definitions and protocols for building and integrating application software. It's sometimes referred to as a contract between an information provider and an information user—establishing the content required from the consumer (the call) and the content required by the producer (the response).

A REST API (also known as RESTful API) is an application programming interface that conforms to the constraints of REST architecture. REST stands for representational state transfer.

REST is a set of architectural principles, not a protocol or a standard. API developers can implement REST in a variety of ways.

When a request is made via a RESTful API, it transfers a representation of the state of the resource to the requester. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XML, or plain text. JSON is the most generally popular because, despite its name, it's language-agnostic, as well as readable by both humans and machines.

REST implies **stateless client-server communication**, meaning no client information is stored between requests and each request is separate and unconnected.

{% embed url="<https://www.youtube.com/watch?v=-MTSQjw5DrM&ab_channel=Fireship>" %}
REST APIs in 100 seconds (and more)
{% endembed %}

### Basic Architecture

![](https://1172597814-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MJ6Mj8gFbz9Ji6QL6Zi%2F-MM_hRRFTOYrwZyikKKn%2F-MM_hhUydzp_XfFnY82q%2FRest-API.png?alt=media\&token=79e2a6f4-52ec-47e4-ba79-f85dc76d4569)

### REST Architectural Constraints

REST APIs must adhere to six architectural constraints:

1. **Client-Server Architecture**: Separation of concerns between client and server, allowing independent evolution of both.
2. **Statelessness**: Each request contains all information needed; the server stores no client context between requests.
3. **Cacheability**: Responses must define themselves as cacheable or non-cacheable to improve performance.
4. **Uniform Interface**: Standardized way of communicating through HTTP methods (GET, POST, PUT, DELETE, PATCH).
5. **Layered System**: Architecture can be composed of hierarchical layers, with each layer having specific functionality.
6. **Code on Demand** (optional): Servers can extend client functionality by transferring executable code.

### Routes and HTTP Methods for a Resource

![Example of REST API routes and specific HTTP methods for a "task" resource](https://1172597814-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MJ6Mj8gFbz9Ji6QL6Zi%2F-MM_fbrFl8WrfQlj8PqN%2F-MM_h2YP2F9WGKUhjgm5%2Ftask_api.png?alt=media\&token=a3a6cc61-aee2-47bb-9c03-8709104bf80e)

#### Standard HTTP Methods

**GET**: Retrieve resource(s) - should be idempotent and safe (no side effects)

**POST**: Create a new resource - not idempotent

**PUT**: Update/replace an entire resource - idempotent

**PATCH**: Partially update a resource - idempotent

**DELETE**: Remove a resource - idempotent

### Advantages of REST APIs

* **Separates User Interface from Application Logic** - enables independent development of frontend and backend
* **Using the same Application Logic for various Client Apps** - a single API can serve websites, mobile apps, IoT devices, and third-party integrations
* **Computationally more efficient** - reduces server load and network traffic by sending UI templates only once and transferring only data
* **Better for horizontally-scaling** - stateless nature allows easy distribution across multiple servers
* **Micro-services friendly** - different APIs can handle different domains (users, products, payments) independently
* **Wide adoption and tooling** - extensive ecosystem of tools, libraries, and developer familiarity
* **Cacheable responses** - improves performance through standard HTTP caching mechanisms

### REST vs GraphQL: A Comparison

While REST remains the dominant API architecture, GraphQL has emerged as an alternative approach for certain use cases. Here's a comprehensive comparison:

| Aspect                           | REST                                                                                | GraphQL                                                                     |
| -------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| **Data Fetching**                | Multiple endpoints, fixed data structure per endpoint                               | Single endpoint, client specifies exact data needed                         |
| **Over-fetching/Under-fetching** | Common issue - endpoints return fixed data structures, often too much or too little | Eliminated - clients request only required fields                           |
| **Versioning**                   | Typically requires version numbers in URLs (e.g., `/api/v1/`, `/api/v2/`)           | Schema evolution without versioning - deprecated fields can coexist         |
| **Learning Curve**               | Simpler, follows HTTP conventions, widely understood                                | Steeper learning curve, requires understanding of query language and schema |
| **Caching**                      | Standard HTTP caching works out-of-the-box (GET requests cached by default)         | More complex - requires custom caching solutions or libraries               |
| **Error Handling**               | Uses HTTP status codes (200, 404, 500, etc.)                                        | Always returns 200 OK, errors in response body                              |
| **Tooling & Ecosystem**          | Mature ecosystem, extensive tools (Postman, Swagger, REST clients)                  | Growing ecosystem, specialized tools (GraphiQL, Apollo, Relay)              |
| **Documentation**                | Manual documentation or tools like Swagger/OpenAPI                                  | Self-documenting through introspection                                      |
| **Network Efficiency**           | Can require multiple round trips for related data                                   | Single request can fetch all nested/related data                            |
| **Type System**                  | No built-in type system (can be added with OpenAPI/Swagger)                         | Strong type system built-in, schema definition language                     |
| **Real-time Updates**            | Requires separate implementation (WebSockets, Server-Sent Events)                   | Built-in subscriptions support for real-time data                           |
| **File Uploads**                 | Straightforward using multipart/form-data                                           | More complex, requires special handling                                     |
| **Monitoring & Analytics**       | Easy to monitor per endpoint, standard HTTP metrics                                 | Harder to monitor - all requests go to single endpoint                      |

#### Typical Use Cases

**REST is ideal for:**

* Public APIs with predictable data access patterns
* Simple CRUD operations
* Microservices architectures with domain-specific services
* Applications where HTTP caching is critical
* Projects with teams familiar with REST conventions
* **Examples**: Twitter API, GitHub API, Stripe API, payment gateways, authentication services

**GraphQL is ideal for:**

* Applications with complex, nested data requirements
* Mobile applications with bandwidth constraints
* Dashboards and analytics platforms with varied data needs
* Applications requiring real-time updates
* Projects with rapidly evolving frontend requirements
* **Examples**: Facebook, GitHub v4 API, Shopify Admin API, content management systems, social media feeds

#### Hybrid Approach

Some organizations use both: REST for simple, predictable operations and GraphQL for complex data aggregation. For instance, REST for authentication/payments and GraphQL for content delivery.

### HTTP Response Codes

HTTP response codes (or status codes) are three-digit numbers returned by a web server in response to an HTTP request made by a client (such as a web browser or a REST API client). These codes indicate the outcome of the request and provide insight into whether the request was successful, encountered errors, or resulted in redirection.

HTTP response codes are grouped into five classes, with each class representing a different type of response. Here's a breakdown:

#### **1xx – Informational Responses**

These status codes indicate that the server has received the request and the client can continue to send more information.

* **100 Continue**: The initial part of the request has been received, and the client should continue with the request.
* **101 Switching Protocols**: The server is switching to the protocol the client requested, such as WebSocket.
* **102 Processing** (WebDAV): The server has received the request, but is still processing it.

#### **2xx – Success**

These status codes indicate that the request was successfully received, understood, and accepted.

* **200 OK**: The request was successful, and the server has returned the requested data.
* **201 Created**: The request was successful, and a new resource has been created as a result.
* **202 Accepted**: The request has been accepted for processing, but it hasn't been completed yet.
* **204 No Content**: The server successfully processed the request, but there is no content to return.
* **206 Partial Content**: The server is delivering only part of the resource due to a range header sent by the client.

#### **3xx – Redirection**

These status codes indicate that the client must take additional actions to complete the request, often involving redirection to another URL.

* **301 Moved Permanently**: The requested resource has been permanently moved to a new URL.
* **302 Found**: The requested resource is temporarily located at a different URL.
* **303 See Other**: The client should retrieve the resource at another URI using a `GET` request.
* **304 Not Modified**: The resource has not been modified since the last request, so the client can use a cached version.
* **307 Temporary Redirect**: Similar to 302, but the method and body should not be changed when following the redirect.
* **308 Permanent Redirect**: Similar to 301, but it keeps the original HTTP method (like `POST` or `PUT`).

#### **4xx – Client Errors**

These status codes indicate that the client made an error in the request.

* **400 Bad Request**: The server couldn't understand the request due to invalid syntax.
* **401 Unauthorized**: Authentication is required and has failed or hasn't been provided.
* **403 Forbidden**: The server understands the request but refuses to authorize it (usually a permissions issue).
* **404 Not Found**: The requested resource could not be found on the server.
* **405 Method Not Allowed**: The request method (like `GET` or `POST`) is not allowed for the requested resource.
* **408 Request Timeout**: The server timed out waiting for the request from the client.
* **409 Conflict**: The request could not be processed because of a conflict with the current state of the resource.
* **410 Gone**: The requested resource is no longer available and has been permanently removed.
* **429 Too Many Requests**: The client has sent too many requests in a given amount of time (rate limiting).

#### **5xx – Server Errors**

These status codes indicate that the server encountered an error and could not complete the request.

* **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
* **501 Not Implemented**: The server does not support the functionality required to fulfill the request.
* **502 Bad Gateway**: The server, while acting as a gateway or proxy, received an invalid response from an upstream server.
* **503 Service Unavailable**: The server is not ready to handle the request (due to maintenance or overloading).
* **504 Gateway Timeout**: The server, while acting as a gateway or proxy, did not get a response from the upstream server in time.
* **505 HTTP Version Not Supported**: The server does not support the HTTP protocol version used in the request.

#### **Commonly Used HTTP Response codes in practice**

* **200 OK**: Everything went fine (often seen in web pages and API requests).
* **404 Not Found**: The requested URL or resource does not exist (common for broken links).
* **500 Internal Server Error**: Something went wrong on the server's side, and the request couldn't be processed.
* **403 Forbidden**: The user does not have the necessary permissions to access the requested resource.
* **401 Unauthorized**: Authentication failed or wasn't provided, and access to the resource is denied.

These codes provide essential feedback for users and developers to understand the status of their HTTP requests and troubleshoot issues accordingly.

### Common HTTP code mistakes

Here are some simple examples of common HTTP response codes that are often mistakenly used or misunderstood:

#### **1. Mistaken use of `404 Not Found` instead of `410 Gone`**

**Scenario: A blog post was deleted permanently.**

* **Mistaken Response**: `404 Not Found`

  **Explanation**: Many developers return a `404` when a resource (like a blog post) is missing. However, `404` means the resource **may never have existed**, or it could just be temporarily unavailable.
* **Correct Response**: `410 Gone`

  **Explanation**: `410 Gone` should be used when a resource has been **intentionally** removed and will not be available again. This tells the client the resource is permanently gone.

#### **2. Mistaken use of `403 Forbidden` instead of `401 Unauthorized`**

**Scenario: A user tries to access a page that requires login, but they are not logged in.**

* **Mistaken Response**: `403 Forbidden`

  **Explanation**: Developers sometimes return `403` when a user is not authenticated. However, `403` means the server understood the request but **refuses to fulfill it**, typically due to permissions (even if the user **is** authenticated).
* **Correct Response**: `401 Unauthorized`

  **Explanation**: `401 Unauthorized` should be returned when authentication is required but has **not been provided** or has **failed** (e.g., invalid credentials).

#### **3. Mistaken use of `500 Internal Server Error` instead of `400 Bad Request`**

**Scenario: A user submits a form with malformed data (e.g., missing required fields or sending invalid JSON).**

* **Mistaken Response**: `500 Internal Server Error`

  **Explanation**: Many developers use `500` as a catch-all for errors, even when the issue is with the **client's request**, not the server. `500` implies a server-side issue.
* **Correct Response**: `400 Bad Request`

  **Explanation**: `400 Bad Request` should be returned when the server cannot process the request due to **client-side errors** (e.g., bad syntax, invalid data).

#### **4. Mistaken use of `302 Found` instead of `307 Temporary Redirect`**

**Scenario: A web page temporarily redirects users to another URL.**

* **Mistaken Response**: `302 Found`

  **Explanation**: Developers sometimes use `302 Found` for temporary redirects. However, `302` can cause **issues with POST/PUT requests** because clients might change the HTTP method to `GET` when following the redirect.
* **Correct Response**: `307 Temporary Redirect`

  **Explanation**: `307` should be used because it ensures that the **original HTTP method** (like `POST`) is maintained when following the redirect.

#### **5. Mistaken use of `204 No Content` instead of `200 OK`**

**Scenario: An API request to update a user's profile is successful, and the server wants to confirm the update.**

* **Mistaken Response**: `204 No Content`

  **Explanation**: Developers sometimes return `204 No Content` when the operation is successful but don't have content to return. However, if the client expects any confirmation, such as a success message, `204` should not be used.
* **Correct Response**: `200 OK`

  **Explanation**: Use `200 OK` when the operation is successful and you need to return some data, such as a confirmation message or updated resource data. If no content is returned, `204` is appropriate, but only when the body is **intentionally empty**.

#### **6. Mistaken use of `405 Method Not Allowed` instead of `400 Bad Request`**

**Scenario: A client sends an invalid request method (like `PATCH` when only `POST` or `GET` are supported).**

* **Mistaken Response**: `405 Method Not Allowed`

  **Explanation**: `405` is meant to indicate that the **requested method** (e.g., `POST`, `GET`) is known by the server but **disabled** or **not allowed** for that resource.
* **Correct Response**: `400 Bad Request`

  **Explanation**: If the method isn't allowed because the client sent a **malformed request** or incorrect HTTP method, then `400 Bad Request` is more appropriate.

### Best practices for REST API design

1. **Use nouns for resource names**: `/users`, `/products`, not `/getUsers` or `/createProduct`
2. **Use HTTP methods correctly**: GET for retrieval, POST for creation, PUT/PATCH for updates, DELETE for removal
3. **Version your API**: Include version in URL (`/api/v1/`) or headers for backward compatibility
4. **Use proper status codes**: Return appropriate HTTP status codes for different scenarios
5. **Implement pagination**: For large datasets, use query parameters like `?page=1&limit=10`
6. **Provide filtering and sorting**: Allow clients to filter (`?status=active`) and sort (`?sort=createdAt:desc`) results
7. **Use HTTPS**: Always use secure connections in production
8. **Document your API**: Provide clear documentation using tools like Swagger/OpenAPI
9. **Implement rate limiting**: Protect your API from abuse with request limits
10. **Use consistent naming conventions**: Stick to either camelCase or snake\_case throughout your API


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mihai-gheorghe.gitbook.io/tic/backend-programming/rest-apis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
