Web API & REST quiz and interview questions
Building and consuming APIs is a daily job for backend developers, so interviews test REST basics hard: which HTTP verb to use, which status code to return, what idempotent means, and how authentication, CORS and versioning work.
Web API & REST: key concepts
- REST
- An API style built around resources (URLs like /orders/42) and standard HTTP verbs. Each request is stateless — it carries everything the server needs.
- HTTP verbs
- GET reads, POST creates, PUT replaces, PATCH updates part of a resource, DELETE removes. GET, PUT and DELETE are idempotent.
- Status codes
- 2xx success (200, 201 Created, 204), 4xx client errors (400, 401, 403, 404, 429), 5xx server errors (500).
- Authentication
- APIs usually use bearer tokens such as JWTs: a signed token with claims, sent in the Authorization header.
- CORS
- Browsers block cross-origin calls unless the API sends CORS headers allowing that origin.
- Versioning and docs
- Version breaking changes (/v1/, headers) and describe the API with OpenAPI/Swagger.
All 45 Web API & REST questions with answers
Try each one first, then open the answer. Making a class test? Use the test maker.
Which HTTP verb is normally used to create a new resource?
- A. GET
- B. POST
- C. DELETE
- D. HEAD
Show answer
B. POST — POST /orders creates an order; the response is usually 201 Created with the new resource's URL.
What is the difference between PUT and PATCH?
- A. None
- B. PUT replaces the whole resource; PATCH changes only some fields
- C. PATCH deletes
- D. PUT is read-only
Show answer
B. PUT replaces the whole resource; PATCH changes only some fields — PUT /users/7 sends the full user; PATCH /users/7 can send just { "email": "..." }.
Which status code fits a successful create?
- A. 200 OK
- B. 201 Created
- C. 204 No Content
- D. 302 Found
Show answer
B. 201 Created — 201 tells the client a new resource exists, usually with a Location header pointing to it.
The client sent invalid JSON fields. Which status code?
- A. 404
- B. 400 Bad Request
- C. 500
- D. 201
Show answer
B. 400 Bad Request — 400 means the request itself is wrong. 404 means the resource doesn't exist; 500 means the server failed.
What is the difference between 401 and 403?
- A. None
- B. 401: not authenticated (who are you?); 403: authenticated but not allowed
- C. 403 means the server crashed
- D. 401 means not found
Show answer
B. 401: not authenticated (who are you?); 403: authenticated but not allowed — No or invalid token → 401. Valid token but missing the Admin role → 403.
Which HTTP verb is NOT idempotent?
- A. GET
- B. PUT
- C. DELETE
- D. POST
Show answer
D. POST — Repeating a POST can create duplicates. Repeating GET, PUT or DELETE leaves the server in the same state.
What does "stateless" mean in REST?
- A. No database
- B. Each request carries everything needed (e.g. a token); the server keeps no session between requests
- C. Responses are never cached
- D. Only GET is allowed
Show answer
B. Each request carries everything needed (e.g. a token); the server keeps no session between requests — Statelessness makes APIs easy to scale — any server instance can handle any request.
A client requests GET /products/999 and no product 999 exists. What status code is returned?
[HttpGet("{id}")] public ActionResult<Product> Get(int id) { var p = _repo.Find(id); if (p == null) return NotFound(); return p; }- A. 200
- B. 204
- C. 404
- D. 500
Show answer
C. 404 — NotFound() produces a 404 response.
What is a JWT?
- A. A JavaScript test
- B. A signed token holding claims (user id, roles, expiry) that the server can verify without a session
- C. An encrypted database
- D. A web template
Show answer
B. A signed token holding claims (user id, roles, expiry) that the server can verify without a session — The signature proves the token wasn't changed. Note: the payload is only Base64-encoded, not encrypted — never put secrets in it.
Your React app on app.example.com can't call api.example.com from the browser. What is the likely cause?
- A. The API is down
- B. CORS — the API doesn't allow that origin
- C. JSON is invalid
- D. DNS
Show answer
B. CORS — the API doesn't allow that origin — Configure the API's CORS policy to allow the front-end origin (and only that origin).
What's wrong with this response?
if (user == null) return Ok(new { error = "User not found" });- A. Nothing
- B. It returns 200 for an error, so clients think it succeeded — return NotFound()
- C. Ok() can't take objects
- D. error must be a number
Show answer
B. It returns 200 for an error, so clients think it succeeded — return NotFound() — Status codes are part of the contract. Return 404 (or a ProblemDetails 4xx) so clients and monitoring see the failure.
Why add rate limiting to a public API?
- A. To make responses smaller
- B. To protect it from abuse and overload — clients over the limit get 429 Too Many Requests
- C. To cache responses
- D. To log errors
Show answer
B. To protect it from abuse and overload — clients over the limit get 429 Too Many Requests — ASP.NET Core has built-in rate-limiting middleware (fixed window, sliding window, token bucket).
Where does [FromQuery] read a value from?
- A. The JSON body
- B. The URL query string, e.g. ?page=2
- C. The route path
- D. A cookie
Show answer
B. The URL query string, e.g. ?page=2 — [FromBody] reads the request body, [FromRoute] reads /items/{id} and [FromQuery] reads ?page=2&size=20.
An endpoint returns 50,000 orders at once and times out. What's the standard fix?
- A. Increase the timeout
- B. Pagination (page/size or cursor) so each response is small
- C. Return XML
- D. Use POST
Show answer
B. Pagination (page/size or cursor) so each response is small — Return pages of results plus a way to get the next page. Cursor-based paging stays fast on very large tables.
Why version an API (e.g. /v1/, /v2/)?
- A. SEO
- B. So breaking changes don't break existing clients
- C. To make it faster
- D. It's required by REST
Show answer
B. So breaking changes don't break existing clients — Old mobile apps can keep calling v1 while new clients use v2 with the changed contract.
What does Swagger/OpenAPI give you?
- A. A database
- B. A machine-readable description of the API, interactive docs and client generation
- C. Authentication
- D. Hosting
Show answer
B. A machine-readable description of the API, interactive docs and client generation — Teams and partners can explore and test endpoints in the browser and generate typed clients.
How do an API controller and an MVC controller typically differ?
- A. They're identical
- B. API controllers return data (JSON); MVC controllers usually return HTML views
- C. API controllers can't use DI
- D. MVC controllers can't return JSON
Show answer
B. API controllers return data (JSON); MVC controllers usually return HTML views — In ASP.NET Core both derive from ControllerBase; [ApiController] adds API-friendly behaviour.
An unhandled exception inside an API action usually produces which status?
- A. 200
- B. 404
- C. 500 Internal Server Error
- D. 401
Show answer
C. 500 Internal Server Error — 5xx means the server failed. Log the details server-side and return a safe error body without stack traces.
Calls to a payment provider sometimes fail for a second. What should the client do?
- A. Fail immediately
- B. Retry with exponential backoff (and an idempotency key for payments)
- C. Retry forever with no delay
- D. Switch to XML
Show answer
B. Retry with exponential backoff (and an idempotency key for payments) — Libraries like Polly add retries, backoff and circuit breakers. Idempotency keys stop a retry charging twice.
What does REST stand for?
- A. Remote Execution Service Tool
- B. Representational State Transfer
- C. Rapid Endpoint Service Technology
- D. Request State Template
Show answer
B. Representational State Transfer — REST is the architectural style described by Roy Fielding: resources, representations (JSON) and standard verbs.
Which URL best follows REST resource naming?
- A. /getAllOrders
- B. /orders
- C. /order_list.php
- D. /api?action=orders
Show answer
B. /orders — Use plural nouns for collections (/orders, /orders/42) and let the HTTP verb say what happens.
A DELETE succeeds and there's nothing to return. Which status code fits?
- A. 200 with an empty body
- B. 204 No Content
- C. 404
- D. 201
Show answer
B. 204 No Content — 204 means success with no response body.
A user signs up with an email that already exists. Which status code fits best?
- A. 500
- B. 409 Conflict
- C. 200
- D. 404
Show answer
B. 409 Conflict — 409 means the request conflicts with the current state of the resource.
What is 422 Unprocessable Entity typically used for?
- A. Server crashes
- B. Well-formed JSON that fails validation rules (e.g. negative quantity)
- C. Missing endpoints
- D. Rate limits
Show answer
B. Well-formed JSON that fails validation rules (e.g. negative quantity) — Some APIs use 400 for all validation errors; 422 separates "invalid syntax" from "valid syntax, invalid values".
What does the HEAD verb do?
- A. Deletes headers
- B. Same as GET but returns only headers, no body
- C. Creates a resource
- D. Uploads files
Show answer
B. Same as GET but returns only headers, no body — Handy for checking whether a resource exists or how big it is without downloading it.
Why does the browser send an OPTIONS request before some cross-origin calls?
- A. To log in
- B. It's a CORS preflight asking the server which methods and headers are allowed
- C. To cache the page
- D. To check SSL
Show answer
B. It's a CORS preflight asking the server which methods and headers are allowed — Requests with custom headers (like Authorization) or methods like PUT trigger a preflight.
What are ETags used for?
- A. Tagging endpoints
- B. Caching and concurrency: clients send If-None-Match / If-Match to avoid re-downloading or overwriting newer data
- C. Logging
- D. Authentication
Show answer
B. Caching and concurrency: clients send If-None-Match / If-Match to avoid re-downloading or overwriting newer data — If the ETag matches, the server can answer 304 Not Modified; If-Match on PUT prevents lost updates.
What is ProblemDetails in ASP.NET Core?
- A. A logging tool
- B. A standard JSON error format (RFC 7807) with type, title, status and detail
- C. A profiler
- D. A database
Show answer
B. A standard JSON error format (RFC 7807) with type, title, status and detail — Consistent error bodies make APIs easier to consume; [ApiController] uses it for validation errors.
What does the client receive?
[HttpPost] public IActionResult Create(OrderDto dto) { var order = _service.Create(dto); return CreatedAtAction(nameof(Get), new { id = order.Id }, order); }- A. 200 with the order
- B. 201 with the order and a Location header pointing to GET /orders/{id}
- C. 204
- D. 302 redirect
Show answer
B. 201 with the order and a Location header pointing to GET /orders/{id} — CreatedAtAction builds the URL of the new resource from the Get action and returns 201.
Why issue short-lived access tokens plus a refresh token?
- A. To use less memory
- B. If an access token leaks it expires quickly; the refresh token (kept safer, revocable) gets new ones
- C. Refresh tokens are faster
- D. It's required by HTTP
Show answer
B. If an access token leaks it expires quickly; the refresh token (kept safer, revocable) gets new ones — Typical setup: 15-minute access tokens and a longer-lived refresh token you can revoke on logout.
What is the difference between OAuth 2.0 and OpenID Connect?
- A. None
- B. OAuth 2.0 is for authorization (access to APIs); OpenID Connect adds authentication (who the user is) on top
- C. OpenID is older
- D. OAuth handles passwords directly
Show answer
B. OAuth 2.0 is for authorization (access to APIs); OpenID Connect adds authentication (who the user is) on top — "Sign in with Google" uses OpenID Connect; granting an app access to your Drive uses OAuth scopes.
Where should an API key or bearer token be sent?
- A. In the URL query string
- B. In a request header (e.g. Authorization: Bearer …)
- C. In the page title
- D. In a cookie named key
Show answer
B. In a request header (e.g. Authorization: Bearer …) — URLs end up in logs, browser history and analytics. Headers over HTTPS keep secrets out of them.
What is a webhook?
- A. A JavaScript hook
- B. An HTTP call a service sends to your URL when an event happens (e.g. payment succeeded)
- C. A browser extension
- D. A cache
Show answer
B. An HTTP call a service sends to your URL when an event happens (e.g. payment succeeded) — Instead of polling Stripe every minute, Stripe POSTs to your webhook endpoint. Verify its signature.
When is gRPC a better fit than REST/JSON?
- A. Public browser APIs
- B. Fast internal service-to-service calls with strict contracts and streaming
- C. SEO pages
- D. File downloads only
Show answer
B. Fast internal service-to-service calls with strict contracts and streaming — gRPC uses HTTP/2 and Protobuf — compact and fast, but not directly callable from browsers without a proxy.
What problem does GraphQL mainly solve?
- A. Database backups
- B. Clients ask for exactly the fields they need in one request, avoiding over- and under-fetching
- C. Authentication
- D. Caching images
Show answer
B. Clients ask for exactly the fields they need in one request, avoiding over- and under-fetching — Great for flexible front ends; trade-offs include harder HTTP caching and query cost control.
What is wrong with this endpoint design?
[HttpGet("deleteUser/{id}")] public IActionResult DeleteUser(int id) { _repo.Delete(id); return Ok(); }- A. Nothing
- B. A GET request changes data — crawlers, prefetching or a link can delete users. Use DELETE /users/{id}
- C. id must be a GUID
- D. Ok() is wrong
Show answer
B. A GET request changes data — crawlers, prefetching or a link can delete users. Use DELETE /users/{id} — GET must be safe (no side effects). Use the DELETE verb and require authorization.
What is model validation's response in an [ApiController] when a [Required] field is missing?
- A. 500
- B. An automatic 400 with ProblemDetails listing the errors
- C. 200 with null
- D. The action runs anyway
Show answer
B. An automatic 400 with ProblemDetails listing the errors — [ApiController] checks ModelState before your action and returns a ValidationProblemDetails 400.
Which header tells the server the request body is JSON?
- A. Accept: application/json
- B. Content-Type: application/json
- C. Authorization
- D. Cache-Control
Show answer
B. Content-Type: application/json — Content-Type describes what you send; Accept says what you want back.
What does an idempotency key on a POST protect against?
- A. Slow responses
- B. Duplicate processing when a client retries the same request (e.g. charging twice)
- C. SQL injection
- D. CORS errors
Show answer
B. Duplicate processing when a client retries the same request (e.g. charging twice) — The server remembers the key and returns the original result for a repeated request.
Which approach keeps an API backward compatible?
- A. Renaming fields
- B. Adding new optional fields and endpoints instead of changing or removing existing ones
- C. Changing status codes
- D. Removing old endpoints immediately
Show answer
B. Adding new optional fields and endpoints instead of changing or removing existing ones — Additive changes don't break clients; breaking changes need a new version and a deprecation period.
What is HATEOAS?
- A. A security standard
- B. Responses include links to related actions/resources so clients can navigate the API
- C. A caching header
- D. A database pattern
Show answer
B. Responses include links to related actions/resources so clients can navigate the API — E.g. an order response with links to cancel or pay. It's part of strict REST, though many APIs skip it.
What does HTTPS add to an API?
- A. Faster responses
- B. Encryption and server identity checks, so tokens and data can't be read or altered in transit
- C. Compression
- D. Caching
Show answer
B. Encryption and server identity checks, so tokens and data can't be read or altered in transit — Never send credentials or tokens over plain HTTP.
What is a typical way to secure service-to-service API calls without a user?
- A. No security
- B. OAuth client credentials (client id + secret → access token) or mTLS
- C. Hard-coded passwords in URLs
- D. Cookies
Show answer
B. OAuth client credentials (client id + secret → access token) or mTLS — The client-credentials flow gives a machine its own scoped access token.
Why log a correlation ID with each request?
- A. For SEO
- B. To trace one request across services and logs when debugging
- C. To cache responses
- D. To authenticate
Show answer
B. To trace one request across services and logs when debugging — Pass an X-Correlation-ID header between services and include it in every log line.
What does the Accept-Language or Accept header let a client do?
- A. Upload files
- B. Ask for a preferred language or response format (content negotiation)
- C. Authenticate
- D. Set cookies
Show answer
B. Ask for a preferred language or response format (content negotiation) — The server picks the best match it supports and says what it returned via Content-Type / Content-Language.
More subjects
Need software for your business instead? I'm an AI automation & full-stack developer — see what I build.