Autocoder

REST API Interview Questions and Answers

Last updated 2026-11-19

REST questions look simple until the follow-ups arrive: is PUT idempotent, when do you return 409 instead of 400, how would you paginate a feed, where does authentication belong. This page answers the common ones precisely, includes a small runnable Flask example with correct status codes, and flags the distinctions that interviewers like to probe.

It fits with microservices questions and system design questions. Data stores behind APIs are covered in MongoDB and DBMS pages. For the whole backend loop, read how to crack a backend interview.

Core ideasResources, HTTP semantics, statelessness
Often probedIdempotency, status codes, pagination, auth
LevelEasy to medium

Safe and idempotent methods

A small API with correct status codes

The Flask example creates a book (201 with a Location header), reads it (200 or 404) and rejects bad input (400). It is short enough to write in an interview.

python
from flask import Flask, jsonify, request
app = Flask(__name__)
books, next_id = {}, 1

@app.post("/books")
def create():
    global next_id
    data = request.get_json(silent=True) or {}
    if not data.get("title"):
        return jsonify(error="title is required"), 400
    books[next_id] = {"id": next_id, "title": data["title"]}
    resp = jsonify(books[next_id]); resp.status_code = 201
    resp.headers["Location"] = f"/books/{next_id}"
    next_id += 1
    return resp

@app.get("/books/<int:book_id>")
def read(book_id):
    b = books.get(book_id)
    return (jsonify(b), 200) if b else (jsonify(error="not found"), 404)

REST API Interview Questions and Answers: questions with worked answers

  1. 1

    What is REST and what are its constraints?

    easy

    REST (Representational State Transfer) is an architectural style for networked systems, usually over HTTP. Its constraints are client-server separation, statelessness (each request carries all the information needed), cacheability, a uniform interface (resources identified by URIs, manipulated through representations, self-descriptive messages), a layered system and optional code on demand. An API that follows these loosely is commonly called RESTful; strictly, hypermedia (HATEOAS) is part of the uniform interface, though few APIs implement it.

  2. 2

    Which HTTP methods are used for CRUD, and which are idempotent?

    easy

    POST creates, GET reads, PUT replaces, PATCH partially updates and DELETE removes. GET, PUT and DELETE are idempotent: sending them several times has the same effect as once (a second DELETE may return 404, but the state is the same). POST is not idempotent, as two POSTs can create two resources. This distinction matters for retries: idempotent requests can be retried safely after a timeout.

  3. 3

    PUT versus PATCH versus POST?

    medium

    POST submits data for the server to process, typically creating a subordinate resource at a server-chosen URI. PUT replaces the entire resource at a known URI, so omitted fields are reset; it is idempotent. PATCH applies a partial change, such as {"status": "shipped"}; it can be idempotent but is not required to be (an "increment by one" patch is not). Use PUT when the client sends the full representation and PATCH for small updates.

  4. 4

    List the status codes you should know and when to use them.

    medium

    200 OK for successful reads or updates. 201 Created with a Location header after creation. 202 Accepted for asynchronous work. 204 No Content for success without a body, such as DELETE. 301 and 302 for redirects, 304 Not Modified for conditional GETs. 400 Bad Request for malformed input. 401 Unauthorized when authentication is missing or invalid. 403 Forbidden when the caller is authenticated but not allowed. 404 Not Found. 405 Method Not Allowed. 409 Conflict for state conflicts such as a duplicate or version mismatch. 422 Unprocessable Entity for semantically invalid data. 429 Too Many Requests. 500 for server errors, 502 and 504 for upstream failures, 503 when unavailable.

  5. 5

    What is the difference between 401 and 403?

    medium

    401 means the request lacks valid authentication: no token, an expired token or bad credentials, and the response should say how to authenticate. 403 means the server knows who you are and refuses because you lack permission. Some APIs return 404 instead of 403 for resources a user should not even know exist, to avoid leaking their existence.

  6. 6

    How should you design URLs for resources?

    medium

    Use nouns for resources and let the HTTP method express the action: GET /orders/42, not /getOrder?id=42. Use plural collections, and nest only to express ownership: /users/7/orders. Keep hierarchies shallow, use lowercase and hyphens, and use query parameters for filtering, sorting and paging: /orders?status=shipped&sort=-created. For operations that do not fit CRUD, model them as resources, such as POST /orders/42/cancellation.

  7. 7

    How do you version a REST API?

    medium

    Common approaches are a path prefix (/v1/orders), a header (Accept: application/vnd.example.v2+json) or a query parameter. The path is the most visible and cache friendly. Prefer evolving without breaking: add fields rather than removing them, keep old behaviour for existing clients and announce deprecation with a sunset date. Bump the version only for breaking changes.

  8. 8

    How do you implement pagination, and what are the trade-offs?

    medium

    Offset pagination (?page=3&size=20) is simple and allows jumping to a page, but deep offsets are slow and concurrent inserts shift results. Cursor pagination (?after=<opaque cursor>&limit=20) uses an indexed position, stays fast and consistent, but gives no random page access. Return the next cursor, or a Link header or next URL, and cap the maximum page size. See system design questions for the scale argument.

  9. 9

    How would you secure a REST API: sessions, JWT and OAuth 2.0?

    medium

    Always use HTTPS. Server-side sessions store state on the server and send an opaque id in a cookie; they are easy to revoke but need shared storage when scaled. A JWT is a signed token the client sends in the Authorization header, so servers verify it without lookups; it is hard to revoke before expiry, so keep access tokens short and use refresh tokens. OAuth 2.0 is a framework for delegated authorisation, letting an app act for a user without their password, typically via the authorisation code flow with PKCE. Also validate input, enforce authorisation on every resource and rate limit.

  10. 10

    How do you make POST requests safe to retry?

    hard

    Accept an Idempotency-Key header that the client generates per logical operation. The server stores the key, request fingerprint and response, ideally in the same transaction as the side effect, with a unique constraint on the key. A repeat with the same key returns the stored response, and a repeat with a different body is rejected with an error. This lets clients retry after timeouts without creating duplicate orders or payments.

  11. 11

    What is statelessness and why does it matter?

    medium

    Each request contains everything the server needs, including credentials, and the server keeps no client session state between requests. Any server instance can then handle any request, which allows horizontal scaling, simple load balancing and easy recovery from failures. State, where needed, lives in the client, a token or a shared data store. See load balancing questions.

  12. 12

    REST versus GraphQL versus gRPC?

    medium

    REST uses many resource URLs with fixed responses, benefits from HTTP caching and is the most widely understood, but can cause over-fetching or many round trips. GraphQL exposes one endpoint where the client specifies the fields it needs, which cuts round trips for varied clients but makes caching, rate limiting and query cost control harder. gRPC uses Protocol Buffers over HTTP/2 with strongly typed contracts and streaming, and is efficient for service-to-service calls but is less convenient from browsers. Choose by consumer: public APIs often REST, internal services often gRPC, complex client-driven UIs sometimes GraphQL.

  13. 13

    How does HTTP caching apply to REST APIs?

    medium

    GET responses can be cached by browsers and proxies using Cache-Control and validators. An ETag lets the client send If-None-Match, and the server answers 304 Not Modified if the resource is unchanged. Last-Modified with If-Modified-Since does the same with timestamps. For optimistic concurrency, clients can send If-Match with the ETag on PUT, and the server returns 412 Precondition Failed if the resource changed. Use Vary headers when the response depends on request headers. See caching questions.

  14. 14

    What is a good error response format?

    medium

    Return the right status code and a consistent JSON body with a machine-readable code, a human-readable message and, for validation, the offending fields: {"error": {"code": "VALIDATION_FAILED", "message": "title is required", "fields": ["title"]}}. RFC 9457 (problem details) standardises this. Never leak stack traces or internal details, and include a request id so support can find the matching log entry.

Frequently asked questions

Is REST the same as HTTP?

No. REST is an architectural style. HTTP is a protocol, and REST APIs commonly use it. You can use HTTP without following REST.

Is a REST API always JSON?

No. REST is representation agnostic, though JSON is by far the most common.

What is HATEOAS?

Hypermedia as the engine of application state: responses include links to the next possible actions. It is part of strict REST but rarely used in practice.

What is the difference between REST and SOAP?

SOAP is an XML protocol with a strict envelope and WS-* standards. REST is a lighter style that uses HTTP semantics directly and many data formats.

Related guides

More in CS Fundamentals Interview Questions

See all in this section