# REST: Name Resources With URLs, Use HTTP Methods, and Keep Servers Stateless

> REST is a style for web APIs. It models data as resources with URLs, uses standard HTTP methods to act on them, and keeps the server free of memory about past requests.

**In short:** REST is a style for web APIs that models data as resources with URLs, uses standard HTTP methods to act on them, and keeps the server free of memory about past requests.

From "System design", a free course by Venkat R. Murty: https://designervenkat.online/learn/system-design/rest

## What You Will Learn

This lesson explains REST, a style for designing web APIs. An API is a set of addresses and rules that lets one program ask another program for data or for an action. A web API does this over web addresses and web messages.

You will learn three big ideas. First, REST treats each thing the system manages as a resource with its own URL. Second, clients use standard HTTP methods to act on those resources. Third, the server keeps no memory of earlier requests, so any server can answer the next one. You will then see these ideas in a food delivery app and weigh the costs of the style.

- **API:** Application Programming Interface. The set of requests a program can make to another program, and the answers it gets back.
- **REST:** Representational State Transfer. A style of design for web APIs that follows a few named rules, such as resources, uniform methods, and statelessness.
- **Resource:** Any thing the system can name and act on, such as an order, a user, or a menu.
- **URL:** Uniform Resource Locator. The web address of one resource, such as /orders/42.
- **HTTP method:** The first word of a web request. It says what the client wants to do, such as GET to read or DELETE to remove.
- **Status code:** A short number in the answer that says what happened, such as 200 for success or 404 for not found.
- **Representation:** The data the server sends back that describes a resource at that moment.
- **JSON:** JavaScript Object Notation. A plain-text format that writes data as named fields inside curly braces.
- **Stateless:** The server keeps no memory of earlier requests from a client. Each request must stand on its own.

## What Are Resources and URLs?

REST was defined by Roy Fielding in his 2000 doctoral dissertation at the University of California, Irvine. He wanted rules that would let a network-based system grow to a very large size. One of his main ideas is a uniform interface, which means every resource is reached in the same way.

In REST, the resource is the unit you design around. Give each resource a stable URL. The URL should point at the thing itself, not at a job you want done to it. The client then picks an HTTP method to say what it wants to happen.

### Why Use Nouns, Not Verbs?

Write URLs with nouns. A noun names a thing you can point at. A verb names a job. REST puts the job in the method, so the URL stays short and steady over time.

- **Good: /orders/42:** This is a noun for one order. The number picks the order. The method then tells the server what to do with it.
- **Bad: /cancelOrder?id=42:** The action sits inside the address. Each new action then needs a new address, and the design grows messy.
- **Collections: /orders:** This names the whole list of orders. A GET reads the list, and a POST adds one new order to it.

> **Tip:** Plural nouns such as /orders are common. Pick one naming style and use it everywhere, so a reader can guess the next address.

## What Are HTTP Methods and Status Codes?

HTTP is the set of rules that browsers and servers use to send requests and answers. Each request begins with a method, which is sometimes called an HTTP verb. The method says what the client wants. The URL says which resource the method applies to. The four methods used most in REST are below.

- **GET:** Reads a resource. The server sends back a representation, usually as JSON. A GET should only read and should not change data.
- **POST:** Sends new data, often to create something or to start a process. Each POST may change the server, so it is not repeat-safe.
- **PUT:** Replaces a resource with the data the client sends. The client sends the full new version of the resource.
- **DELETE:** Removes the resource at that URL. A successful delete may send back a 204 code, which means success with no body.

The answer carries a status code. A status code is a short number that tells the client what happened. Code 200 means the request worked. Code 404 means the server found no resource at that address. Honest status codes let a client react without reading the text of the answer.

> **Tip:** Never change data with a GET. Browsers, link previews, and crawlers may repeat a GET on their own, so a GET that changes data can cause real harm.

### What Are Safe and Idempotent Methods?

Two words describe how methods behave. A method is safe if it does not change the server's state. A method is idempotent if sending the same request once or many times leaves the server in the same state. All safe methods are idempotent. GET is safe. PUT and DELETE are idempotent but not safe, because they do change data. POST is neither, because sending it twice can create two records.

The status code can still differ between repeats. The first DELETE of an item may return 200, while a second DELETE of the same item returns 404. The server state is the same in both cases, which is what idempotent means. How clients should retry these calls belongs to a later lesson.

## What Is Statelessness?

Stateless means the server keeps no memory of earlier requests from a client. Here, state means facts a server holds about a client between requests, such as who is logged in or what is in a shopping cart. In a stateless design, each request carries all the information the server needs to answer it.

Fielding listed statelessness as one of the core constraints of REST. In his description, session state stays entirely on the client. The server does not have to remember anything about that client between calls.

### What a Request Must Carry

- **The method and the address:** The request says which resource it means and which action to take on it.
- **Proof of who is asking:** Many REST APIs send a login token, such as a JSON Web Token, with every request. The server checks the token each time instead of remembering the login.
- **The data needed for the answer:** A request that creates an order includes the order details in its body. The server does not look back at an earlier request to fill them in.

### Why Stateless Servers Scale

Scaling means handling more users by adding more machines. If a server keeps each user's session in its own memory, the next request from that user must reach the same machine. This is called a sticky session, and it makes adding or moving machines hard.

When every request stands alone, any server instance can answer it. A load balancer, which is a device that spreads requests across machines, can send each request anywhere. Fielding also noted that servers can free their resources quickly when they do not keep state between requests.

> **Tip:** Put user facts in a shared database or in the token the client sends. Do not keep them only in one server's memory.

## Uniform, Cacheable Responses

A uniform interface means each resource is handled in the same way across the whole API. A client that knows how to read one order can read another resource the same way. Responses usually use one data format, most often JSON. Fielding described four constraints that make the interface uniform, including naming resources and sending messages that describe themselves.

GET responses can also be cached. A cache is a stored copy of an answer, kept so it can be reused later without asking the server again. Because GET only reads, a cache can hold its answer safely. Fielding said a response labeled as cacheable lets a client reuse that data for later equal requests.

### Trade-Offs to Know

- **A standard shape fits no screen exactly:** One uniform format serves many clients, but it may not suit one screen. Fielding noted that a uniform interface can lose some efficiency, because data travels in a general form.
- **Over-fetching:** A fixed endpoint such as GET /orders/42 may return more fields than a screen needs. The extra data uses bandwidth and time.
- **Many round trips:** A screen that needs an order, its restaurant, and its driver may make three calls. Each call is one round trip, meaning one trip to the server and back.
- **Stale cached copies:** A cached answer can be out of date. Fielding warned that stale cached data can make a system less reliable.
- **Repeated data:** Because the server keeps no memory, every request must repeat some information. Fielding said this repeated data can slow a series of requests.

## Worked Example: Order Tracking

Imagine a food delivery app. Its order-tracking screen shows the status of one order. The app talks to a REST API. Here is how the main calls work, one step at a time.

1. **Read the order:** When the screen opens, the app sends GET /orders/42. The server reads order 42 and sends back its data as JSON. The request changes nothing, so the app can repeat it safely.
2. **Place a new order:** When the customer taps Place order, the app sends POST /orders with the order details in the body. The server creates the order and replies with a status code and, usually, the address of the new order.
3. **Cancel the order:** When the customer taps Cancel, the app sends DELETE /orders/42. The server removes the order. A later GET for order 42 finds nothing.
4. **Let any server answer:** The app sends its login token with each call. Each request holds all it needs, so a load balancer may send each call to a different server. Every server gives the same answer, because the order data sits in shared storage.

The sample below models the same idea in a few lines. It keeps no session memory. Its answer depends only on the method, the path, and the shared order store.

```python
# One shared store of orders, and a handler that needs only the request.
orders = {42: {'id': 42, 'status': 'preparing'}}

def handle(method, path):
    if method == 'GET' and path == '/orders/42':
        if 42 in orders:
            return 200, orders[42]
        return 404, None
    if method == 'DELETE' and path == '/orders/42':
        if 42 in orders:
            del orders[42]
            return 204, None
    return 404, None

print(handle('GET', '/orders/42'))
print(handle('DELETE', '/orders/42'))
print(handle('GET', '/orders/42'))
print(handle('DELETE', '/orders/42'))

```

Output:

```text
(200, {'id': 42, 'status': 'preparing'})
(204, None)
(404, None)
(404, None)

```

The output shows the rules at work. The first GET returns the order with a 200 code. The DELETE removes it and returns 204. After that, both the GET and the second DELETE find nothing and return 404. Because the handler only reads the method, the path, and the shared store, any copy of it on any machine gives the same answers.

> **Tip:** A real app might model cancel as a status change, such as setting the order's status to cancelled with PUT or PATCH. Both designs can follow REST. Choose the one that matches your business rules.

## Check Yourself

Try these two short scenarios. Each one needs the ideas from this lesson.

**Quick check:** A shopping app sends POST /addItemToCart and POST /getCartContents. The server keeps each user's session in its own memory, so a request works only on the server that handled the login. Which answer names the two breaks and a fix?

A. The design is fine. Only the server name needs a change, since POST can carry data and sessions are fast.
B. Only the method is wrong. Change both calls to PUT, and the server can keep the session in memory.
C. The URLs use verbs, and reads use POST. The server also holds sessions. Use nouns such as /carts/{id}/items, GET for reads, and a token on every request so any server can answer.
D. The problem is the login. Remove it, so every user sees the same cart.

**Answer:** C. There are two breaks. The URLs name actions instead of resources, and reads use POST, which should be a safe GET. Also, the server remembers the session, so only one machine can answer. A redesign names carts and items as nouns, reads with GET, and sends a token with each request.

**Quick check:** A delivery app's order screen must show the current status of order 42 each time it opens. Which request fits REST best?

A. POST /getOrderStatus, with the order number in the body
B. GET /orders/42
C. DELETE /orders/42/status
D. PUT /orders/42/read-status-now

**Answer:** B. Reading a resource is a GET on its noun URL. A GET only reads and changes nothing. The other options put an action word in the address or use a method that changes data for a simple read.

## Key Takeaways

REST asks you to name resources with nouns and to act on them with standard HTTP methods. Use status codes that tell the truth. Keep the server free of session memory, so any server can answer any request. These rules make APIs easier to scale and cache. They also cost some efficiency, because responses follow one general shape and clients may need extra calls.

## Sources

- [Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, Chapter 5: Representational State Transfer (REST)](https://roy.gbiv.com/pubs/dissertation/rest_arch_style.htm)
- [MDN Web Docs: HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods)
- [MDN Web Docs glossary: Idempotent (source file)](https://github.com/mdn/content/blob/main/files/en-us/glossary/idempotent/index.md)
- [http.dev: HTTP Methods explained](https://http.dev/methods)
- [Microsoft Azure Architecture Center: Best practices for RESTful web API design](https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design)
- [Wikipedia: REST](https://en.wikipedia.org/wiki/REST)
- [Strapi: RESTful API Design Guide, Principles and Best Practices](https://strapi.io/blog/restful-api-design-guide-principles-best-practices)
- [TechMarcos: Designing RESTful APIs for Modern Backend Architecture](https://www.techmarcos.com/designing-restful-apis/)
- [Mastering REST API Design: The Art of Resources and Methods (Medium)](https://medium.com/@thantheinthwin.dev/mastering-rest-api-design-resources-methods-best-practices-14ad117c6fe6)
