KAHIBARO
Discord Login Register

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:

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:

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:

Example answer (spoken):

A REST API exposes resources using URLs and uses HTTP methods to act on them. For example, GET /users to list users or DELETE /users/10 to 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”

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.

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:

Example:

Bad (stateful idea):

Good (stateless):

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.

MethodTypical useShould have body?Should be idempotent?
GETRead dataNoYes
POSTCreate / actionYesNo
PUTReplace whole resourceYesYes
PATCHPartially update resourceYesNot guaranteed, but often treated as idempotent
DELETERemove resourceOptionalYes

Example mapping:

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?

Example:

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:

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:

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 with Content-Type, to tell the client what we can send with Accept, and for caching control. For example, a POST that creates a user can return 201 Created with a Location header pointing to /users/123.

API Design Questions

10. How do you design RESTful URLs?

Common rules:

Example answer:

I design URLs around resources, usually with plural nouns, like /users and /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

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:

json
{
  "items": [/* list of users */],
  "total": 230,
  "page": 2,
  "size": 20
}

Or links:

json
{
  "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=20 returns the second page with 20 users and fields like total to help the client build pagination controls.

13. How do you design error responses?

Give a consistent JSON structure, for example:

json
{
  "error": "ValidationError",
  "message": "Email is invalid",
  "details": {
    "email": ["Invalid email format"]
  }
}

Or:

json
{
  "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 an error type, a human readable message, and a details object 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:

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/v1 and 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:

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:

  1. Format / schema:
    • Types, required fields, lengths.
    • For example, email is string, age is integer.
  2. Business rules:
    • For example, password minimum length, age >= 18.
  3. Security:
    • No unexpected fields, safe file types, sanitized inputs.

Typical flow for POST /users:

Example answer:

I validate requests with a schema or model, so each field has a type and constraints. For example, I check that email is present and formatted correctly and that password has 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?

json
      {
        "email": "a@example.com",
        "password": "secret123"
      }

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:

Use response models or DTOs that contain only allowed fields.

Example:

Internal user model:

json
{
  "id": 10,
  "email": "a@example.com",
  "password_hash": "...",
  "role": "admin"
}

Public response:

json
{
  "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:

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?

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:

  1. Client sends credentials, for example POST /login with email and password.
  2. Server verifies credentials.
  3. Server returns a token, for example a JWT.
  4. Client stores the token and sends it in Authorization: Bearer <token> header to other endpoints.
  5. 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:

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:

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:

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:

From client side:

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:

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:

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:

Endpoints:

MethodPathDescription
POST/todosCreate todo
GET/todosList todos (with pagination, filters)
GET/todos/{id}Get single todo
PATCH/todos/{id}Update part of todo
DELETE/todos/{id}Delete todo

Filters:

Example answer:

I would have a Todo resource with id, title, completed, and due_date. For creation I use POST /todos with a JSON body. To list todos I use GET /todos with pagination and optional filters like completed and due_before. To get a single todo I use GET /todos/{id}, to update fields like completed I use PATCH /todos/{id}, and to delete I use DELETE /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:

Example answer:

For file uploads I expose an endpoint like POST /files that accepts multipart/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:

  1. Synchronous but only for short operations.
  2. Asynchronous with background jobs:
    • Client calls POST /reports.
    • Server creates a background job and responds with 202 Accepted and a job ID.
    • Client polls GET /reports/{job_id} until status is completed.

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:

  1. Start simple, with a clear definition.
  2. Give an HTTP example, for example, a URL, method, and status code.
  3. Mention best practices in one sentence, for example:
    • "I would also use proper status codes and validation."
  4. 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

Comments

Please login to add a comment.

Don't have an account? Register now!