33.8. API Interview Questions
Table of Contents
Introduction
This chapter gives you practical API interview questions, what the interviewer is really asking, and how to answer them clearly as a junior backend developer. Use it to prepare short, confident answers and simple examples you can explain on a whiteboard or in a call.
Focus on:
- Explaining concepts in your own words.
- Using HTTP examples.
- Showing you understand trade-offs, not just definitions.
You do not need to know everything perfectly. You do need to show you can reason about APIs safely and clearly.
Rule: In interviews, always connect your answer to HTTP methods, status codes, validation, security, and versioning whenever it makes sense. These are core API topics.
Conceptual Questions
1. What is an API?
How to answer:
An API is a defined way for one piece of software to talk to another. It defines:
- What you can do, for example, "create a user", "list orders".
- How you call it, for example, HTTP method, URL, headers, body.
- What you get back, for example, status code and JSON response.
Example answer (spoken):
An API is a contract that lets one application interact with another. In web backends, we usually expose HTTP APIs where clients send requests to URLs like /users with methods like GET or POST, and the server responds with a status code and JSON data.
2. What is a REST API?
How to answer:
REST is a style of building HTTP APIs based on:
- Resources available at URLs, for example
/users,/orders/123. - Standard HTTP methods to perform actions on those resources, for example GET, POST, PUT, PATCH, DELETE.
- Statelessness each request contains everything needed, the server does not store client session state between calls.
- Use of HTTP status codes and media types like
application/json.
Example answer (spoken):
A REST API exposes resources using URLs and uses HTTP methods to act on them. For example,GET /usersto list users orDELETE /users/10to delete user 10. It is stateless, so every request includes what the server needs, like auth and data, and the server responds with proper HTTP status codes and usually JSON.
3. Explain “resource” and “endpoint”
- Resource: A type of thing your API manages, like
User,Order,Product. - Endpoint: A concrete path and method, for example:
- Resource:
User - Endpoints:
GET /users(list users)POST /users(create user)GET /users/{id}(get user by id)
Example answer:
A resource is a logical object in the system, like “user” or “order.” An endpoint is a specific URL plus method that operates on that resource, for example GET /orders/123 is an endpoint that returns the order resource with id 123.
4. REST vs RPC vs GraphQL
You do not need deep GraphQL knowledge, but you should know the idea.
- REST: Resource oriented, many endpoints, each returns fixed shapes.
- RPC style HTTP: Procedure oriented, endpoints like
/createUser,/calculatePrice. - GraphQL:
- Single endpoint, often
POST /graphql. - Client sends a query describing which fields it wants.
- Reduces over fetching and under fetching.
Safe junior answer:
REST focuses on resources and uses standard HTTP methods like GET and POST. RPC style APIs expose actions as methods, like /createUser, and are more function oriented. GraphQL usually uses a single endpoint where the client specifies exactly which fields it wants, which can avoid multiple REST calls. For most typical backend work, REST is the default, and GraphQL is chosen when clients need flexible queries.
5. What does “stateless” mean in REST?
Stateless means:
- The server does not remember previous requests from the client.
- Each request includes all needed information, such as:
- Authentication token.
- Pagination parameters.
- Any other context.
Example:
Bad (stateful idea):
- Client:
GET /next-page - Server: “I remember your last page was 2, so here is page 3.”
Good (stateless):
- Client:
GET /users?page=3&limit=20 - Server: Just returns page 3, no memory needed.
Example answer:
Stateless means every request is independent. The server does not store session state between calls. The client must send all required information, like auth tokens and pagination data, with each request. This makes it easier to scale horizontally, because any server can handle any request.
HTTP-Specific Questions
6. Explain common HTTP methods: GET, POST, PUT, PATCH, DELETE
You should be able to give clear CRUD examples.
| Method | Typical use | Should have body? | Should be idempotent? |
|---|---|---|---|
| GET | Read data | No | Yes |
| POST | Create / action | Yes | No |
| PUT | Replace whole resource | Yes | Yes |
| PATCH | Partially update resource | Yes | Not guaranteed, but often treated as idempotent |
| DELETE | Remove resource | Optional | Yes |
Example mapping:
GET /userslist users.GET /users/10get user 10.POST /userscreate a new user.PUT /users/10replace user 10 data.PATCH /users/10update part of user 10, for example only email.DELETE /users/10delete user 10.
Example answer:
GET is for reading data and should not change server state. POST usually creates a resource or triggers an action and is not idempotent. PUT replaces an existing resource completely and is idempotent, so calling it multiple times has the same effect as calling it once. PATCH partially updates a resource. DELETE removes a resource and should be idempotent as well.
7. What are idempotent and safe methods?
- Safe method: Should not change server state. Example: GET.
- Idempotent method:
- Multiple identical requests have the same effect as one request.
- GET, PUT, DELETE are defined as idempotent.
- POST is not idempotent.
Example:
DELETE /users/10:- First call deletes user 10.
- Second call, user 10 is already gone, result is the same state. Idempotent.
Example answer:
A safe method does not change server state, like GET. An idempotent method can change state, but doing the same request multiple times results in the same final state, like PUT or DELETE. This matters for retries in clients and proxies.
8. Explain common HTTP status codes used in APIs
You should know at least:
- 2xx success
200 OKsuccessful request.201 Createdresource successfully created.204 No Contentsuccess with no body, often for DELETE or PUT.- 4xx client errors
400 Bad Requestinvalid request data or format.401 Unauthorizedmissing or invalid auth token.403 Forbiddenauthenticated but not allowed.404 Not Foundresource does not exist or not exposed.409 Conflictversion conflict or duplicate resource.422 Unprocessable Entityvalidation error in request body.- 5xx server errors
500 Internal Server Errorunexpected error.503 Service Unavailableservice is down or overloaded.
Example answer:
For a successful GET I would return 200. For a successful POST that created a resource I would use 201 and usually include the newly created resource in the body and its URL in the Location header. For validation errors I prefer 422 with a JSON structure that explains which fields are wrong. For unauthorized requests I use 401, and for missing resources 404.
9. What are HTTP headers and why are they important for APIs?
Headers carry metadata about:
- Request, for example:
Authorization: Bearer <token>Content-Type: application/jsonAccept: application/json- Response, for example:
Content-Type: application/jsonCache-Control: no-storeLocation: /users/10Set-Cookie: session=...; HttpOnly; Secure
Example answer:
Headers carry extra information that is not part of the main body. For APIs we use headers for authentication, to describe content types withContent-Type, to tell the client what we can send withAccept, and for caching control. For example, a POST that creates a user can return201 Createdwith aLocationheader pointing to/users/123.
API Design Questions
10. How do you design RESTful URLs?
Common rules:
- Use nouns, not verbs:
- Good:
/users,/orders/123 - Bad:
/createUser,/getAllUsers - Use plural resource names:
/users,/products. - Use path parameters for identities and hierarchy:
/users/{user_id}/users/{user_id}/orders- Use query parameters for filters and pagination:
/users?page=2&limit=20/products?category=books&sort=price_desc
Example answer:
I design URLs around resources, usually with plural nouns, like/usersand/users/{id}. I use path parameters for resource IDs and nested resources, such as/users/{id}/orders. I use query parameters for optional filters and pagination, such as/users?page=2&limit=20. Actions usually map to HTTP methods instead of verbs in the path.
11. Path parameters vs query parameters
- Path parameters:
- Part of the URL path.
- Identify a specific resource or nested resource.
- Example:
/users/10/orders/5. - Query parameters:
- After
?in the URL. - For filters, pagination, sorting, optional settings.
- Example:
/products?category=books&sort=price_desc.
Example answer:
Path parameters are used when the value is part of the resource identity, like/users/10. Query parameters are used for optional filters or options, like/users?active=true&page=2. If removing the parameter changes which resource you refer to, it belongs in the path. If it changes how you view a collection, it belongs in the query string.
12. How do you handle pagination in an API?
Basic patterns:
- Offset / limit:
GET /users?offset=0&limit=20- Page / size:
GET /users?page=2&size=20- Response includes metadata:
{
"items": [/* list of users */],
"total": 230,
"page": 2,
"size": 20
}Or links:
{
"items": [/* list */],
"next": "/users?page=3&size=20",
"prev": "/users?page=1&size=20"
}Example answer:
I usually use page and size or offset and limit as query parameters. The response contains the items and some metadata like total count, current page, and page size. For example,GET /users?page=2&size=20returns the second page with 20 users and fields liketotalto help the client build pagination controls.
13. How do you design error responses?
Give a consistent JSON structure, for example:
{
"error": "ValidationError",
"message": "Email is invalid",
"details": {
"email": ["Invalid email format"]
}
}Or:
{
"code": "INVALID_EMAIL",
"message": "Email must be a valid address",
"field": "email"
}Rule: Always combine a meaningful status code with a clear, consistent error body. Never return raw stack traces to clients.
Example answer:
I use proper HTTP status codes and a consistent JSON structure. For example, for a validation error I might return 422 with a body that has anerrortype, a human readablemessage, and adetailsobject mapping field names to problems. This makes it easy for clients to show user friendly error messages.
14. How do you handle versioning in APIs?
Common strategies:
- In the path:
/api/v1/users/api/v2/users- In header, for example:
Accept: application/vnd.myapp.v1+json
Safest for beginners: version in the path.
Example answer:
To avoid breaking old clients, I version APIs. The simplest is to include a version in the path, like/api/v1and later/api/v2. When we need breaking changes we add a new version and keep the old one for some time, so old clients still work.
15. How do you make APIs backward compatible?
Strategies:
- Only add fields, do not remove or rename existing ones.
- Make new fields optional.
- Do not change meaning of existing fields.
- For breaking changes, introduce new version or new endpoint.
Example answer:
I try to evolve APIs in a backward compatible way by adding new optional fields instead of removing or renaming existing ones. If I must change behavior or remove fields, I create a new version or a new endpoint and keep the old one for existing clients for a while.
Validation and Data Questions
16. How do you validate API requests?
You validate at three levels:
- Format / schema:
- Types, required fields, lengths.
- For example,
emailis string,ageis integer. - Business rules:
- For example, password minimum length, age >= 18.
- Security:
- No unexpected fields, safe file types, sanitized inputs.
Typical flow for POST /users:
- Check
Content-Type: application/json. - Parse JSON.
- Validate schema.
- Validate business rules.
- If error, return
422 Unprocessable Entitywith details.
Example answer:
I validate requests with a schema or model, so each field has a type and constraints. For example, I check thatpasswordhas a minimum length. If validation fails, I return a 422 status code with a JSON body describing the fields that failed so the client can fix them.
17. What is the difference between request body and query parameters?
- Request body:
- For main data, especially in POST, PUT, PATCH.
- Typically JSON.
- Example:
POST /users- Body:
{
"email": "a@example.com",
"password": "secret123"
}- Query parameters:
- For filtering, sorting, pagination, options.
- Always text in the URL after
?.
Example answer:
I use the body for main resource data, especially for create and update operations, usually as JSON. I use query parameters for filters and options, like ?page=2&sort=created_at. For example, creating a user uses a JSON body with fields like email and password, while listing users might use query parameters for pagination.
18. How do you return partial data or hide sensitive fields?
You should never return:
- Passwords.
- Password hashes, if possible.
- Secret tokens.
- Internal IDs, when not needed.
Use response models or DTOs that contain only allowed fields.
Example:
Internal user model:
{
"id": 10,
"email": "a@example.com",
"password_hash": "...",
"role": "admin"
}Public response:
{
"id": 10,
"email": "a@example.com",
"role": "admin"
}Example answer:
I never return sensitive fields like passwords or password hashes. I define response models that only include safe fields, such as id, email, and role. Internally the database model can have more fields, but the API always uses a separate representation for responses.
Authentication and Security Questions
19. How do you secure an API?
As a junior, mention these points:
- Transport security:
- Use HTTPS, not HTTP.
- Authentication:
- Tokens (like JWT or random tokens).
- Or sessions with cookies.
- Authorization:
- Check permissions for each endpoint.
- Input validation:
- Validate all request data.
- Rate limiting:
- Limit number of requests to prevent brute force and abuse.
- CORS configuration:
- Only allow necessary origins.
Example answer:
I secure an API by using HTTPS, requiring authentication for protected endpoints, and checking permissions inside handlers. I validate all incoming data to avoid injection issues. For exposed APIs I also add rate limiting and configure CORS so only allowed frontends can call the API. Secrets like tokens or keys are stored in environment variables, not in code.
20. What is the difference between authentication and authorization in APIs?
- Authentication: Who are you?
- Verifies identity, for example, by checking a token or password.
- Authorization: What are you allowed to do?
- Based on roles or permissions, decides if the authenticated user can access a resource.
Example answer:
Authentication verifies the identity of the client, for example with a JWT or a session cookie. Authorization checks if that authenticated user has permission to perform a specific action, such as viewing an admin panel or deleting a resource.
21. How does token based authentication work in APIs?
Simple flow:
- Client sends credentials, for example
POST /loginwith email and password. - Server verifies credentials.
- Server returns a token, for example a JWT.
- Client stores the token and sends it in
Authorization: Bearer <token>header to other endpoints. - Server checks the token for each request.
Example answer:
In token based auth the client logs in once with credentials. If successful the server returns a token, for example a JWT. The client stores the token and sends it on each request in the Authorization header. The server validates the token and uses it to know which user is making the request.
22. How do you handle CORS in APIs?
CORS is a browser security feature that blocks frontends in one origin from calling APIs in another origin unless allowed.
Server must send headers like:
Access-Control-Allow-Origin: https://my-frontend.comAccess-Control-Allow-Methods: GET, POST, PUT, DELETEAccess-Control-Allow-Headers: Content-Type, Authorization
Example answer:
CORS is enforced by browsers when a frontend runs on a different origin than the API. To allow it, the API must respond with CORS headers like Access-Control-Allow-Origin. In practice, I configure the backend framework or reverse proxy to allow only the specific frontend origins and needed methods and headers, not a wildcard in production.
Performance, Caching, and Reliability Questions
23. How do you make an API performant?
Basic levers:
- Database:
- Use indexes.
- Avoid N+1 queries.
- Use pagination.
- Caching:
- Cache frequent read results in memory or Redis.
- Reduce payload size:
- Return only needed fields.
- Use pagination instead of huge lists.
- Asynchronous processing:
- Move heavy jobs to background workers.
Example answer:
I start with good database queries and indexes, avoid loading too much data at once by using pagination, and cache frequent reads. For heavy operations I move the work to background jobs, so the API can respond quickly and the client can poll or receive a notification when the job is done.
24. How do you use HTTP caching for APIs?
You can use:
Cache-Controlheader, for example:Cache-Control: public, max-age=60ETag/If-None-Matchfor conditional requests:- Server returns
ETag: "xyz". - Client sends
If-None-Match: "xyz". - If unchanged, server returns
304 Not Modified.
Example answer:
For responses that do not change often, I add Cache-Control headers, for example Cache-Control: public, max-age=60, so browsers or CDNs can cache the response. For more advanced caching I can use ETags and return 304 Not Modified when content has not changed, which saves bandwidth.
25. How do you handle timeouts and retries in APIs?
From server side:
- Use timeouts on:
- Database calls.
- External API calls.
- Do not block forever.
- For background tasks, implement retry with backoff.
From client side:
- Set HTTP timeouts.
- Retry idempotent operations only, for example GET or PUT.
Rule: Only automatically retry idempotent operations. Never blindly retry POST requests that create resources, to avoid duplicates.
Example answer:
On the server I set timeouts for database and external API calls and handle errors gracefully, returning a 5xx if something fails. On the client side it is safe to retry idempotent operations like GET or PUT a few times with a backoff delay, but I avoid automatic retries for POST requests that create new resources to prevent duplicates.
Testing and Documentation Questions
26. How do you test APIs?
You should mention at least:
- Unit tests for business logic.
- Integration tests that call the API endpoints.
- Use tools like pytest and a test database.
- Test:
- Happy paths.
- Validation errors.
- Auth failures.
- Edge cases like missing resources.
Example answer:
I write unit tests for the core business logic and integration tests that call the actual HTTP endpoints, for example using pytest and a test client. I test the normal cases, error paths like invalid input or missing authentication, and edge cases like 404s. For database tests I use a separate test database or transactions that roll back after each test.
27. How do you document an API?
Ways:
- OpenAPI / Swagger:
- Many frameworks auto generate documentation.
- Human friendly docs:
- Overview of resources.
- Request and response examples.
- Authentication description.
- Error formats.
Example answer:
I like to use OpenAPI so tools like Swagger UI can auto generate docs with all endpoints, parameters, and schemas. I also provide examples of requests and responses, explain authentication, and describe common error responses. Good docs let frontend developers and external consumers use the API without reading the code.
Practical / Scenario Questions
28. Design an API for a simple todo list
Explain design, not full code.
Resources:
Todowith fields:id,title,completed,due_date.
Endpoints:
| Method | Path | Description |
|---|---|---|
| POST | /todos | Create todo |
| GET | /todos | List todos (with pagination, filters) |
| GET | /todos/{id} | Get single todo |
| PATCH | /todos/{id} | Update part of todo |
| DELETE | /todos/{id} | Delete todo |
Filters:
/todos?completed=true&due_before=2024-12-31&page=1&size=20
Example answer:
I would have aTodoresource with id, title, completed, and due_date. For creation I usePOST /todoswith a JSON body. To list todos I useGET /todoswith pagination and optional filters likecompletedanddue_before. To get a single todo I useGET /todos/{id}, to update fields likecompletedI usePATCH /todos/{id}, and to delete I useDELETE /todos/{id}. All responses are JSON and use standard status codes like 201 for creation and 404 for missing IDs.
29. How would you handle file uploads in an API?
Concepts:
- Use
POSTwithmultipart/form-data. - Limit file size and allowed types.
- Store metadata in database, file in storage.
Example answer:
For file uploads I expose an endpoint likePOST /filesthat acceptsmultipart/form-data. I validate the file size and content type, save the file to disk or object storage, and store a record in the database with the file path and metadata. The API responds with an ID and maybe a download URL.
30. How would you handle long running operations?
Options:
- Synchronous but only for short operations.
- Asynchronous with background jobs:
- Client calls
POST /reports. - Server creates a background job and responds with
202 Acceptedand a job ID. - Client polls
GET /reports/{job_id}until status iscompleted.
Example answer:
For long running operations I avoid blocking the request. Instead, I accept the request, enqueue a background job, and return a 202 with a job ID or status URL. The client can poll that endpoint until the job is finished and then download the result.
How to Use This in an Interview
When answering API questions:
- Start simple, with a clear definition.
- Give an HTTP example, for example, a URL, method, and status code.
- Mention best practices in one sentence, for example:
- "I would also use proper status codes and validation."
- If you are not sure, say what you know and what you would check.
If you prepare a few concrete examples like the todo API and user registration API, you can reuse them across many questions.
Views: 8
KAHIBARO