Skip to content
ADevGuide Logo ADevGuide
Go back

What Is a REST API? Principles, Examples and Interview Questions

Updated:

By Pratik Bhuite | 19 min read

Hub: Web Fundamentals / Networking and Protocols

Series: Backend Interview Mastery

Last updated: Aug 30, 2026

Part 3 of 32 in the Backend Interview Mastery

Key Takeaways

On this page
Reading Comfort:

What Is a REST API? Principles, Examples and Interview Questions

An interviewer asks you to design an order endpoint. Saying “I would use JSON and a POST request” is only the start. A strong answer explains which resource is changing, how retries avoid duplicate orders, what status code a client receives, and how the contract evolves without breaking mobile apps.

REST is not simply JSON over HTTP. It is a design style for exposing resources predictably so clients can integrate, cache, retry, and evolve safely. This guide turns the concept into the production and interview decisions backend engineers are expected to explain. Start with client-server architecture for the request path, then use the Backend Developer Interview Guide for the wider learning path.

Table of Contents

Open Table of Contents

Quick Definition

REST (Representational State Transfer) is an architectural style where:

  1. Data is modeled as resources (for example, users, orders, products).
  2. Resources are identified by URLs.
  3. Clients use standard HTTP methods (GET, POST, PUT, PATCH, DELETE).
  4. Each request contains all context needed to process it (stateless interactions).
  5. Responses use standard HTTP status codes and predictable payloads.

If someone asks, “What is a REST API?” a practical answer is:

“It is an HTTP API designed around resources and standard web semantics so different clients can integrate consistently.”

What Interviewers Look For

Interviewers rarely need a recitation of every REST constraint. They want to see whether you can turn web standards into a dependable client contract. Start by modeling an order, user, or payment as a resource; choose a method whose semantics match the operation; then explain the observable outcome with a status code and a stable response shape.

The differentiator is production judgment. A POST request can time out after the server has created the order, so a client may retry even though it cannot tell whether the first attempt succeeded. Calling out an idempotency key, validation, authentication, and a consistent error body shows that you understand the gap between a happy-path endpoint and an API other teams can safely depend on.

Why REST Became the Default for Web Backends

REST aligned naturally with the web:

  1. HTTP was already everywhere.
  2. Load balancers, CDNs, proxies, and gateways understand HTTP semantics.
  3. Teams can reuse standards for auth, caching, retries, compression, and observability.

This reduces operational friction. In most teams, REST is still the fastest path to shipping a stable external API.

If you are new to request/response flow, start with How APIs Work: A Simple Guide for Beginners and then come back to REST constraints.

Core REST Ideas in Plain English

1. Resources first

Model nouns, not verbs:

  • Better: /users/42/orders/9001
  • Worse: /getUserOrdersById

2. Uniform interface

Use standard methods and status codes consistently. Clients should not need endpoint-specific “special behavior” for basic operations.

If HTTP concepts feel fuzzy, this HTTP vs HTTPS beginner guide is a useful refresher before API design interviews.

3. Stateless requests

Each request includes required context (auth token, parameters, payload). The server should not depend on hidden session state for API correctness.

This maps directly to client-server architecture basics: clients send intent, servers enforce rules, and state transitions stay explicit.

4. Cache-aware design

GET responses can be cached when appropriate, reducing latency and backend load.

5. Layered system compatibility

A request may pass through CDN, WAF, gateway, and service mesh before reaching your service. REST over HTTP works well across these layers.

How a REST Request Flows End to End

flowchart TD
    A[Client App] --> B[DNS and TLS]
    B --> C[API Gateway]
    C --> D{Request type}
    D -->|GET order| E[Authenticate and authorize]
    E --> F[(Cache)]
    F --> G{Cache hit?}
    G -->|Yes| H[200 OK response]
    G -->|No| I[(Primary database)]
    I --> H
    D -->|POST order| J[Validate and authorize]
    J --> K{Idempotency key seen?}
    K -->|Yes| L[Return saved response]
    K -->|No| M[Apply business rules]
    M --> N[Persist and emit event]
    N --> O[201 Created]
    H --> P{Retry needed?}
    O --> P
    L --> P
    P -->|Yes| C
    P -->|No| Q[Done]

    classDef api fill:#e8f0fe,stroke:#1a73e8,stroke-width:2px,color:#000000;
    class A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q api;

This flow highlights why REST APIs are operationally friendly:

  1. A read can use a cache without turning a cache miss into a write.
  2. A create can validate, persist, and return the same result safely on a retry.
  3. Standard edge handling makes routing, observability, and error semantics consistent.

Resource and URL Design

Good URL design makes APIs easier to learn and maintain.

Practical rules:

  1. Use plural nouns for collections: /users, /orders.
  2. Use hierarchical paths for ownership/relationships: /users/{userId}/orders.
  3. Keep URLs stable; avoid embedding volatile implementation details.
  4. Use query params for filtering and pagination, not action commands.

Examples:

  • GET /orders?status=shipped&limit=20
  • GET /orders/ord_1024
  • POST /orders
  • PATCH /orders/ord_1024

Avoid RPC-like endpoints unless there is a real command use case (for example, /orders/{id}/cancel can be valid if cancellation is a business action with state rules).

HTTP Methods in REST APIs

GET

Read-only fetch. Should not mutate state.

POST

Create a resource or trigger a non-idempotent action.

PUT

Replace a full resource representation.

PATCH

Apply partial updates.

DELETE

Delete a resource (or mark it deleted, depending on business requirements).

Method semantics matter because client SDKs, gateways, caches, and observability tooling depend on them.

Idempotency: The Retry-Safety Contract

Network failures make retries unavoidable. A request can reach the server and commit a payment, while the response is lost on its way back to the client. If the client retries a naïve POST /orders, the backend may create a second order or charge a card twice.

For operations with costly side effects, accept an Idempotency-Key and store the key with the request fingerprint and completed response. A retry with the same key returns the original result; a reused key with different request data should fail clearly rather than silently doing the wrong work. This costs storage and an expiry policy, but it is much cheaper than reconciling duplicate payments. A dedicated idempotency article later in this series builds on this foundation.

Status Codes and Error Models

Status codes should tell clients what happened without guesswork.

Common set:

  1. 200 OK for successful reads/updates.
  2. 201 Created when a new resource is created.
  3. 204 No Content for successful operations without body.
  4. 400 Bad Request for validation failures.
  5. 401 Unauthorized for missing/invalid authentication.
  6. 403 Forbidden for valid identity but insufficient permissions.
  7. 404 Not Found when resource does not exist.
  8. 409 Conflict for concurrency/business conflicts.
  9. 429 Too Many Requests for rate-limited requests.
  10. 500 and 503 for server-side failures.

Keep error response shape consistent:

{
  "error": "validation_failed",
  "message": "quantity must be greater than 0",
  "requestId": "req_9f8c2b",
  "details": [
    {
      "field": "quantity",
      "issue": "min_value"
    }
  ]
}

Statelessness, Caching, and Performance

Stateless APIs scale more easily because any instance can process any request.

Caching strategy in practice:

  1. Browser/app cache for short-lived reads.
  2. CDN cache for safe public GETs.
  3. In-memory cache (Redis) for hot keys.
  4. Database as source of truth.

Caching must include invalidation strategy. Many performance incidents come from stale-cache bugs, not slow code.

For a broader path across these foundations, use the Web Fundamentals hub and then drill into APIs by browsing the API tag archive.

Versioning and Backward Compatibility

REST APIs evolve continuously. Breaking clients in production is expensive, so compatibility rules matter.

A pragmatic strategy:

  1. Prefer additive changes (new optional fields).
  2. Keep old fields during migration windows.
  3. Use explicit versioning (/v1/...) for breaking changes.
  4. Publish deprecation timelines and migration examples.

If your API is consumed by mobile apps, backward compatibility becomes even more important because old app versions stay active for months.

Common REST API Mistakes to Avoid

  1. Treating REST as “just endpoints” and ignoring method semantics.
  2. Returning 200 for every outcome, forcing clients to parse message strings.
  3. Mixing resource modeling with action-heavy RPC naming everywhere.
  4. Using inconsistent error payloads across services.
  5. Ignoring idempotency for retry-prone operations like payments.
  6. Skipping pagination and filtering strategy until data scale forces emergency redesign.

Real-World Example: Order Management API

Let us design a minimal order API for an e-commerce backend:

  1. POST /orders creates a new order.
  2. GET /orders/{orderId} fetches order details.
  3. GET /orders?userId=u_42&status=paid filters user orders.
  4. PATCH /orders/{orderId} updates allowed fields.
  5. POST /orders/{orderId}/cancel applies business cancellation rules.

Example create request:

POST /api/v1/orders HTTP/1.1
Authorization: Bearer <token>
Content-Type: application/json
Idempotency-Key: 5d34c91f-b78a-4f20-9c2c-e95e0d1f1f1d

{
  "userId": "u_42",
  "items": [
    { "sku": "book-101", "quantity": 2 }
  ],
  "addressId": "addr_73"
}

Example response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  "orderId": "ord_9001",
  "status": "pending_payment",
  "createdAt": "2026-03-12T10:30:00Z"
}

Design choices and trade-offs:

  1. POST /orders/{id}/cancel is action-shaped, but justified because cancel is a business transition with rule checks.
  2. Idempotency key reduces duplicate orders when clients retry on timeout.
  3. PATCH avoids replacing entire order documents when only shipping address or notes change.

Interview Questions

1. What makes an API “RESTful” instead of just “HTTP-based”?

A RESTful API is designed around resources and a uniform interface using HTTP semantics consistently. Many HTTP APIs return JSON, but if they ignore method semantics, status codes, and resource modeling, they are not truly RESTful.

In interviews, I explain this as “protocol vs design discipline.” HTTP is the transport; REST is the architectural style.

2. When should you use PUT vs PATCH?

Use PUT when replacing the full representation of a resource and PATCH when partially updating fields. If partial updates are common, PATCH reduces payload size and accidental data loss from missing fields.

Trade-off: PATCH introduces merge/validation complexity, so teams need clear schema rules for patchable fields.

3. Why is statelessness important for scaling REST APIs?

Statelessness allows any request to be served by any instance, which simplifies horizontal scaling, failover, and load balancing. You avoid sticky-session dependence and reduce hidden coupling between clients and specific servers.

The trade-off is each request carries context (tokens, metadata), increasing payload overhead slightly.

4. What is idempotency, and why does it matter in REST APIs?

Idempotency means repeating the same operation should not create additional side effects after the first successful execution. It matters because network retries are normal in distributed systems.

Without idempotency keys for create/payment endpoints, timeout retries can create duplicate orders or duplicate charges.

5. How do you version REST APIs without breaking clients?

Start with additive changes whenever possible. For breaking changes, introduce a new version path, keep old version operational during migration, and provide explicit deprecation timelines with examples.

A strong rollout plan includes compatibility tests with real client versions, especially mobile clients that update slowly.

6. Is POST /resource/{id}/action anti-REST?

Not always. Pure CRUD modeling is ideal, but real systems include domain actions (approve, cancel, retry). If the action is a meaningful state transition with business constraints, action endpoints can be a pragmatic choice.

The key is consistency: do not mix random action endpoints and resource endpoints without clear modeling principles.

Conclusion

  1. REST is an architectural style and HTTP is the transport; JSON alone does not make an API RESTful.
  2. Resource names, HTTP methods, and status codes are a public contract, not cosmetic conventions.
  3. Stateless requests make scaling and recovery easier, but authentication and business context still need deliberate design.
  4. Cacheability and versioning are compatibility decisions that reduce cost and protect clients over time.
  5. Idempotency turns uncertain network retries into safe, predictable outcomes for orders, payments, and other side effects.

The next topic in this series covers HTTP methods: GET vs POST vs PUT vs PATCH vs DELETE - the method-level decisions behind the REST contract. For the request path that exists beneath that contract, revisit client-server architecture.

References

  1. REST - MDN Web Docs https://developer.mozilla.org/en-US/docs/Glossary/REST
  2. RFC 9110: HTTP Semantics - IETF https://www.rfc-editor.org/rfc/rfc9110
  3. Architectural Styles and the Design of Network-based Software Architectures - Roy Fielding https://ics.uci.edu/~fielding/pubs/dissertation/top.htm

YouTube Videos

  1. “REST API Interview Questions (Beginner Level)” - Exponent https://www.youtube.com/watch?v=faMdrSCVDzc

Share this post on:

Next in Series

Continue through the [object Object] with the next recommended article.

Related Posts

Keep Learning with New Posts

Subscribe through RSS and follow the project to get new series updates.

Was this guide helpful?

Share detailed feedback

Previous Post
What Is CORS? Backend Guide to Preflight and Security
Next Post
Spring Boot @Valid vs @Validated: Key Differences