REST

Fundamentals Security Notes Jan 6, 2025 HTTP
architecture fundamentals api-design http

Definition

When you interact with almost any website or app today, there’s a good chance it’s using REST behind the scenes. REST (Representational State Transfer) is an architectural style - a set of principles for building web services that are simple, scalable, and easy to understand.

The genius of REST is that it builds on top of how the web already works. You know how web browsers request pages using URLs? REST does the same thing for data. Instead of requesting a web page at www.example.com/about, you might request user data at api.example.com/users/123. And just like browsers use different actions (GET to retrieve a page, POST to submit a form), REST APIs use the same HTTP methods to perform different operations on data.

Here’s the core idea: everything in REST is a “resource” - users, products, orders, whatever makes sense for your application. Each resource has a unique URL (like /users/123 for a specific user). You interact with resources using standard HTTP methods: GET to read, POST to create, PUT/PATCH to update, DELETE to remove. Every request is independent - the server doesn’t remember your previous requests, which makes the system simpler and more scalable.

Example

Social Media API: When Twitter shows your timeline, it calls something like GET /tweets?user=following&limit=20. When you post a tweet, it sends POST /tweets with your message. Liking a tweet might be POST /tweets/123/likes. Every action maps to a resource and an HTTP method.

E-commerce Platform: Amazon’s internal APIs likely have resources like /products, /cart, /orders. Adding something to your cart is POST /cart/items. Viewing your order history is GET /orders. Canceling an order is DELETE /orders/456 or PATCH /orders/456 with a status update.

Banking App: Your bank’s mobile app uses REST to GET /accounts (list your accounts), GET /accounts/123/transactions (view transaction history), and POST /transfers (move money). Each action is a clear combination of resource and verb.

Google Maps Integration: When an app needs directions, it might call GET /directions?origin=NYC&destination=LA&mode=driving. The response includes turn-by-turn directions. Everything is stateless - Google doesn’t need to remember that you asked for directions before.

Spotify-like Music Service: Browse playlists with GET /playlists, get a specific one with GET /playlists/456, add a song with POST /playlists/456/tracks, remove it with DELETE /playlists/456/tracks/789. The URL structure makes it obvious what you’re working with.

Analogy

The Restaurant Menu System: Imagine a restaurant where ordering works like REST:

  • The resources are menu items, orders, and reservations
  • GET /menu shows you what’s available
  • POST /orders places a new order
  • GET /orders/table-5 checks the status of table 5’s order
  • DELETE /orders/table-5/item/burger removes the burger from the order
  • PATCH /reservations/123 changes a reservation

Each request is independent - the waiter doesn’t need to remember what you ordered before to take your current request. The menu item names (resources) and actions (HTTP methods) make the whole system intuitive.

The Library System: A library works like a REST API:

  • Resources: books, patrons, loans
  • GET /books lists all books
  • GET /books?available=true filters to available books
  • POST /loans checks out a book (creates a loan)
  • DELETE /loans/789 returns a book
  • GET /patrons/456/loans shows what a specific person has checked out

You don’t need to explain the library’s entire history to check out a book - each transaction stands on its own.

The Post Office: When you mail a package via REST:

  • POST /packages creates a shipment (you get back a tracking number)
  • GET /packages/TRACK123 checks its status
  • PATCH /packages/TRACK123 updates delivery instructions
  • GET /locations/90210/packages finds packages going to that ZIP code

The post office doesn’t need to remember all your previous shipments to process your current one - stateless, independent transactions.

The Vending Machine: A vending machine is accidentally RESTful:

  • Each product slot is a resource with an ID (A1, B2, C3)
  • You GET the display to see what’s available
  • You POST money to add credit
  • You DELETE (select) item A1 to remove it from inventory and receive it
  • Each transaction is independent - the machine doesn’t care about your previous purchases

Code Example


// [RESTful API](https://reference.apios.info/terms/restful-api/) design
// Resources as nouns, HTTP methods as verbs
GET    /api/v1/users          // List users
GET    /api/v1/users/123      // Get specific user
POST   /api/v1/users          // Create user
PUT    /api/v1/users/123      // Update user
PATCH  /api/v1/users/123      // Partial update
DELETE /api/v1/users/123      // Delete user

// RESTful response
[HTTP/1.1](https://reference.apios.info/terms/http-1-1/) 200 OK
Content-Type: application/json
{
  "id": 123,
  "name": "Alice",
  "email": "[email protected]"
}

Diagram

graph LR
C[Client] -->|HTTP Request| S[Server]
S -->|HTTP Response| C
S --- CS[Client-Server]
S --- ST[Stateless]
S --- CA[Cacheable]
S --- LS[Layered]
S --- UI[Uniform Interface]

Security Notes

SECURITY NOTES

CRITICAL: REST is an architectural style. Security comes from proper implementation of HTTP, TLS, and authorization.

RESTful Principles:

  • Client-server: Clear separation of concerns
  • Stateless: Each request contains all information
  • Cacheable: Responses should indicate if cacheable
  • Uniform interface: Consistent API design
  • Layered: Can add intermediaries (caches, gateways)
  • Code on demand: Optional, rarely used

Resource-Oriented Design:

  • Resources not actions: /users/123, not /getUser?id=123
  • HTTP methods: GET (read), POST (create), PUT/PATCH (update), DELETE (delete)
  • Status codes: Appropriate HTTP status codes for each outcome
  • Representations: Multiple formats (JSON, XML) from same endpoint
  • Content negotiation: Accept/Content-Type headers determine format

URI Design Security:

  • Predictable IDs: Sequential IDs reveal resource count; use UUIDs
  • Hide structure: Don’t reveal internal business logic in URIs
  • Version in URI: Include API version (/v1/, /v2/)
  • No sensitive data: Don’t include passwords or tokens in URIs
  • Safe methods: GET, HEAD, OPTIONS should not modify state

Authentication & Authorization:

  • Require HTTPS: Always use HTTPS for REST APIs
  • Token-based auth: Use JWT, OAuth 2.0, or API keys
  • Authorization checks: Verify permissions for every request
  • Consistent policy: Apply same authorization rules for all endpoints
  • Rate limiting: Limit requests per user/IP/key

Error Handling:

  • Standard status codes: Use correct HTTP status codes
  • Error messages: Provide helpful but not too detailed messages
  • Error IDs: Include error codes for support reference
  • No stack traces: Never expose stack traces in responses
  • Consistent format: Use consistent error response format

Versioning:

  • Backward compatible: Maintain compatibility with old versions
  • Deprecation path: Announce and phase out old versions
  • Version header: Include version in header or URI
  • Support window: Define how long versions are supported

Caching:

  • Cache headers: Set Cache-Control, ETag, Last-Modified
  • Sensitive data: Don’t cache sensitive data
  • Cache invalidation: Implement proper cache invalidation
  • CDN integration: Leverage CDN caching for public data

Best Practices

  1. Use nouns for resource names, not verbs (/users not /getUsers)
  2. Use plural nouns for collections (/users not /user)
  3. Use HTTP methods correctly (GET for read, POST for create)
  4. Return appropriate status codes (201 for create, 204 for delete)
  5. Support filtering, sorting, and pagination for collections
  6. Version your API from the start

Common Mistakes

Using verbs in URLs (/getUsers instead of /users), using POST for everything, returning 200 for errors, not supporting content negotiation, ignoring caching headers, over-fetching or under-fetching data.

Standards & RFCs