REST APIs power most of the internet’s integrations today. Whether you’re interviewing for a backend role, full-stack position, or software engineering job, you’ll likely face questions about REST API design, HTTP methods, and authentication patterns. This guide covers 30+ essential interview questions organized by difficulty level, from fundamental concepts to advanced scenarios.
Basic REST API Interview Questions
1. What is a REST API?
REST stands for Representational State Transfer. A REST API is an architectural style for designing networked applications that uses HTTP requests to perform CRUD (Create, Read, Update, Delete) operations on resources. REST APIs communicate using standard HTTP methods and return responses typically in JSON or XML format. They are stateless, meaning each request contains all the information needed to process it without relying on previous requests.
2. What does REST stand for and what are its core principles?
REST stands for Representational State Transfer. The core principles of REST architecture include:
- Statelessness: Each request from a client to server must contain all information needed to process it
- Uniform Interface: Standardized communication between client and server for consistency
- Client-Server Separation: Clear separation of concerns between the user interface and data storage
- Cacheability: Responses must explicitly indicate whether they can be cached
- Layered System: Architecture can be composed of hierarchical layers
- Code on Demand (Optional): Servers can send executable code to clients
3. What are HTTP methods in REST APIs?
HTTP methods define the action to be performed on a resource. The main HTTP methods are:
- GET: Retrieve data from a server without modifying it
- POST: Submit data to a server to create a new resource
- PUT: Replace an entire resource on the server with new data
- DELETE: Remove a resource from the server
- PATCH: Apply partial modifications to a resource
4. What is a URI and how is it used in REST APIs?
A URI (Uniform Resource Identifier) is used to uniquely identify resources on the server. In REST APIs, URIs define the endpoint path through which clients access resources. For example, /api/users/123 identifies a specific user resource with ID 123. URIs should be descriptive, use nouns to represent resources, and follow a consistent naming convention. They should not contain verbs since HTTP methods already indicate the action.
5. What are REST API endpoints?
Endpoints are the URLs or addresses where clients send requests to a REST API. Each endpoint corresponds to a specific resource or collection of resources. For example, /api/products might be an endpoint for retrieving all products, while /api/products/5 retrieves a specific product. Well-designed endpoints are intuitive, follow REST conventions, and are clearly documented.
6. Explain the difference between PUT and PATCH methods.
Both PUT and PATCH are used to update resources, but they differ in scope:
- PUT: Replaces the entire resource with the new data provided. If some fields are not included in the request, they may be deleted or set to null
- PATCH: Applies partial modifications to a resource. Only the fields provided in the request are updated, while other fields remain unchanged
Example: If updating a user with PUT, you must provide all user fields. With PATCH, you can update just the email field while leaving other fields intact.
7. What are HTTP status codes and why are they important?
HTTP status codes indicate the result of an API request. They help clients understand whether a request was successful, if there was an error, or if further action is needed. Status codes are grouped into categories:
- 2xx (Success): Request succeeded (e.g., 200 OK, 201 Created)
- 3xx (Redirection): Further action needed to complete the request
- 4xx (Client Error): Request contains errors or is malformed (e.g., 400 Bad Request, 404 Not Found)
- 5xx (Server Error): Server failed to fulfill a valid request (e.g., 500 Internal Server Error)
8. What is the difference between a 400 and 404 status code?
A 400 Bad Request status code indicates that the client sent a malformed request—the syntax is invalid, required parameters are missing, or the data format is incorrect. A 404 Not Found status code indicates that the requested resource does not exist on the server. In other words, 400 is a client-side problem with the request itself, while 404 means the server understood the request but cannot find the target resource.
9. How does REST API handle authentication?
REST APIs use several authentication mechanisms to verify the identity of clients:
- API Keys: A simple token passed in the request header to identify the client
- Basic Authentication: Username and password encoded in Base64 sent with each request
- Bearer Tokens: Tokens (often JWT) passed in the Authorization header
- OAuth 2.0: A delegated authorization framework allowing third-party access
10. What are request headers and what is their purpose?
Request headers provide metadata about the HTTP request. Common REST API headers include:
- Content-Type: Describes the media type of the resource being sent (e.g., application/json)
- Authorization: Carries credentials for authenticating the client
- Accept: Specifies the media types the client can process in the response
- Cache-Control: Defines caching behavior for the response
Intermediate REST API Interview Questions
11. What is API versioning and why is it important?
API versioning allows developers to make changes to an API without breaking existing client applications. There are several versioning strategies:
- URL Versioning: Include version in the URL path (e.g., /api/v1/users or /api/v2/users)
- Header Versioning: Specify version in request headers (e.g., Accept: application/vnd.api+v2)
- Query Parameter Versioning: Pass version as a query parameter (e.g., /api/users?version=2)
Versioning is crucial for maintaining backward compatibility while allowing the API to evolve and improve over time.
12. What is idempotency and how is it implemented in REST APIs?
Idempotency means that calling the same request multiple times produces the same result as calling it once. This is important for handling network failures and retries. GET, PUT, DELETE, and HEAD methods are idempotent—repeating them doesn’t change the outcome. POST is not idempotent by default because each call creates a new resource. Implementing idempotency involves using unique identifiers or tokens to detect and prevent duplicate operations.
13. Explain the concept of statelessness in REST APIs.
Statelessness means that each request contains all the information required for the server to process it. The server does not store client context or session information between requests. Every request is independent and must include necessary data like authentication tokens, user information, or request parameters. This design improves scalability because servers don’t need to maintain session state, allowing easy load balancing across multiple servers.
14. What is caching in REST APIs and how does it improve performance?
Caching stores copies of API responses to avoid redundant requests. REST APIs indicate caching behavior through HTTP headers like Cache-Control and ETag. The Cache-Control header specifies how long a response can be cached (e.g., max-age=3600 for one hour). Caching reduces server load, decreases bandwidth usage, and improves client response times. Different caching strategies include private caching (only the client caches), public caching (proxies and clients can cache), and time-based expiration.
15. What is CORS and why is it important for REST APIs?
CORS (Cross-Origin Resource Sharing) is a security feature that controls which domains can access a REST API. By default, browsers prevent cross-origin requests for security reasons. CORS allows a server to specify which origins are allowed to make requests. The server uses response headers like Access-Control-Allow-Origin to permit or restrict access. This is essential for public APIs that need to be accessed from web applications running on different domains.
16. What is the Richardson Maturity Model?
The Richardson Maturity Model grades RESTful APIs based on their adherence to REST principles:
- Level 0: Uses HTTP only as a transport system for RPC calls (not truly REST)
- Level 1: Introduces resources through distinct endpoints
- Level 2: Utilizes HTTP verbs (GET, POST, PUT, DELETE) and proper response codes
- Level 3: Implements hypermedia controls (HATEOAS) for full REST compliance
Most modern APIs operate at Level 2. Level 3 includes hypermedia links in responses that guide clients to related resources, enabling true RESTful design.
17. What is HATEOAS and how does it enhance REST APIs?
HATEOAS (Hypermedia As The Engine Of Application State) is a Level 3 REST constraint where API responses include links to related resources and actions. Instead of clients hardcoding URLs, the API provides navigation links. For example, a user response might include links to view all users, update the user, or delete the user. This makes APIs more discoverable and resilient to URL changes since clients follow provided links rather than constructing URLs.
18. How should error responses be structured in a REST API?
Error responses should be structured and consistent, typically returning JSON with relevant information:
- An appropriate HTTP status code (4xx for client errors, 5xx for server errors)
- An error code or identifier for programmatic handling
- A human-readable error message describing what went wrong
- Additional context or details to help debugging
Example error response:
{
"error": {
"code": "INVALID_REQUEST",
"message": "Email field is required",
"details": "The 'email' parameter is missing from the request body"
}
}
Structured error responses enable clients to parse errors programmatically and take appropriate actions.
19. What are rate limits and how are they implemented?
Rate limiting restricts the number of requests a client can make within a specific time period. This protects APIs from abuse and ensures fair resource distribution. Rate limits are typically implemented using:
- Header-based tracking: Using HTTP headers like X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset
- 429 Too Many Requests response: Returned when rate limit is exceeded
- Token bucket algorithm: Clients receive tokens that are consumed with each request
20. How would you secure a REST API?
Securing a REST API involves multiple layers:
- Authentication: Verify client identity using API keys, tokens, or OAuth
- Authorization: Ensure authenticated clients can only access permitted resources
- HTTPS/TLS: Encrypt data in transit using SSL/TLS protocols
- Input Validation: Sanitize and validate all client inputs to prevent injection attacks
- Rate Limiting: Prevent abuse through request throttling
- CORS Configuration: Restrict cross-origin access appropriately
Advanced REST API Interview Questions
21. Design a REST API for an e-commerce platform that handles product searches and filtering.
For an e-commerce platform, the REST API design would include:
- GET /api/v1/products: Retrieve all products with pagination
- GET /api/v1/products?category=electronics&price_min=100&price_max=500: Search and filter products by category and price range
- GET /api/v1/products/{productId}: Retrieve details of a specific product
- POST /api/v1/products: Create a new product (admin only)
- PUT /api/v1/products/{productId}: Update an entire product
- PATCH /api/v1/products/{productId}: Partially update product fields
- DELETE /api/v1/products/{productId}: Remove a product
Query parameters enable flexible filtering without creating multiple endpoints. The API would return 200 for successful retrieval, 201 for creation, 400 for invalid queries, 404 for missing products, and 401 for unauthorized users.
22. How would you handle pagination in a REST API serving large datasets?
Pagination divides large datasets into manageable chunks. Implement pagination using query parameters:
GET /api/v1/users?page=2&limit=20
Response includes:
{
"data": [...],
"pagination": {
"page": 2,
"limit": 20,
"total": 500,
"pages": 25,
"has_next": true,
"has_previous": true
}
}
This approach reduces memory usage, improves response times, and provides metadata for client navigation. Alternative strategies include offset-based, cursor-based (for better performance with large datasets), and keyset pagination.
23. Explain how to implement proper logging and monitoring for a REST API.
Effective logging and monitoring helps track API behavior and troubleshoot issues:
- Request Logging: Log incoming requests with method, endpoint, client IP, and timestamp
- Response Logging: Capture response status codes, processing time, and response size
- Error Logging: Log errors with stack traces and context for debugging
- Performance Metrics: Track response times, request rates, and resource usage
- Security Logging: Monitor authentication failures, authorization errors, and suspicious patterns
- Alerting: Set up alerts for errors, performance degradation, or unusual activity
24. How would you handle versioning for an API used by multiple clients with different version requirements?
URL versioning is most practical for multiple client versions. Maintain multiple versions of your API concurrently:
- /api/v1/ for legacy clients
- /api/v2/ for newer clients with enhanced features
- /api/v3/ for the latest version
Deprecate old versions with a timeline communicated to clients. Each version runs as a separate codebase or branch, allowing independent maintenance. Include a deprecation header in responses of older versions to notify clients: Deprecation: true, Sunset: date
25. Describe a scenario where you need to handle circular dependencies in related REST API resources.
Circular dependencies occur when resources reference each other. For example, a User has Orders, and Orders belong to a User. Handle this by:
- Partial Representation: In the User response, include only essential Order details (ID and link), not the complete Order object
- Links to Related Resources: Provide URLs to fetch full details separately:
"orders_url": "/api/v1/users/123/orders" - Query Parameter Control: Allow clients to specify depth:
/api/v1/users/123?expand=orders,orders.items
This prevents response bloat and infinite nesting while maintaining data accessibility.
26. How would you implement webhook functionality for real-time event notifications in a REST API?
Webhooks allow the API to push events to client-specified URLs when something happens:
- Register Webhooks: POST /api/v1/webhooks with event types and callback URL
- Event Triggers: When events occur, send HTTP POST requests to registered webhooks
- Retry Logic: Implement exponential backoff to retry failed webhook deliveries
- Verification: Sign webhook payloads with HMAC to verify authenticity
- Management Endpoints: GET, UPDATE, DELETE webhooks to manage subscriptions
Webhooks provide real-time notifications without clients polling the API repeatedly, reducing load and improving responsiveness.
27. Design a REST API for handling file uploads with progress tracking and resumable uploads.
Handle large file uploads efficiently:
- Initiate Upload: POST /api/v1/uploads to create an upload session, receive session ID
- Chunk Upload: PUT /api/v1/uploads/{sessionId}/chunk/{chunkNumber} to upload file chunks
- Progress Tracking: GET /api/v1/uploads/{sessionId} returns uploaded percentage and received chunks
- Complete Upload: POST /api/v1/uploads/{sessionId}/complete to finalize and process the file
- Resumable: If interrupted, clients can resume by uploading remaining chunks to the same session
This approach enables large file uploads, progress visibility, and recovery from interruptions.
28. How would you design a REST API that supports both synchronous and asynchronous operations?
Different operations have different timing requirements:
- Synchronous: For quick operations (< 1 second), return results immediately with 200 status
- Asynchronous: For long-running operations, accept the request (202 Accepted), return a job ID, and allow status polling
Example asynchronous flow:
- POST /api/v1/reports/generate returns 202 with job ID
- GET /api/v1/reports/jobs/{jobId} returns processing status
- Webhook notifies when processing completes
29. Explain how you would implement search and filtering across multiple fields in a REST API.
Support flexible search and filtering:
GET /api/v1/products?search=laptop&category=electronics&brand=Dell&price_min=500&price_max=2000&sort=price&order=asc
Implementation considerations:
- Use query parameters for each filterable field
- Support full-text search via a “search” parameter
- Enable sorting and ordering with “sort” and “order” parameters
- Validate and sanitize all filter inputs to prevent SQL injection
- Use database indexing on frequently searched fields for performance
- Document all supported filters and search operators
30. How would you handle API backward compatibility when making breaking changes?
Sometimes breaking changes are necessary. Manage them carefully:
- Announce Deprecation: Notify users 3-6 months before removing features using deprecation headers and documentation
- Provide Migration Path: Clearly document how to update client code to use new endpoints
- Support Multiple Versions: Maintain v1 and v2 simultaneously during transition period
- Sunset Timeline: Set a clear deadline for v1 shutdown
- Migration Assistance: Offer tools or scripts to help clients update
This approach respects existing clients while enabling API evolution.
31. Design a REST API for a real-time notification system used by multiple applications.
A notification system must be reliable and performant:
- POST /api/v1/notifications: Send notifications to users/channels
- GET /api/v1/notifications: Retrieve user notifications with filtering and pagination
- PUT /api/v1/notifications/{notificationId}: Mark notifications as read
- DELETE /api/v1/notifications/{notificationId}: Delete notifications
- Webhook Subscriptions: Subscribe to notification events
Implementation should include delivery guarantees, retry mechanisms, and prioritization for critical notifications. Integration with push services ensures timely delivery across devices.
32. How would you optimize a REST API for mobile clients with limited bandwidth and battery?
Mobile optimization strategies:
- Minimal Payloads: Return only essential fields, allow clients to request specific fields via query parameters
- Compression: Enable gzip compression for responses
- Caching: Use strong Cache-Control headers to reduce repeated requests
- Connection Pooling: Reuse HTTP connections to reduce overhead
- Batch Requests: Provide endpoints to fetch multiple resources in a single request
- Progressive Loading: Return critical data first, load secondary data asynchronously
33. Describe how to implement request/response transformation and sanitization in a REST API.
Data transformation ensures consistency and security:
- Input Validation: Check data types, formats, and constraints before processing
- Sanitization: Remove potentially harmful characters and code from inputs
- Data Transformation: Convert between client format and storage format
- Output Filtering: Remove sensitive fields before returning responses
- Serialization: Convert internal objects to JSON/XML for clients
This protects against injection attacks and ensures data integrity throughout the API lifecycle.
34. How would you test a REST API comprehensively?
Comprehensive testing includes:
- Unit Tests: Test individual endpoint logic in isolation
- Integration Tests: Test endpoints with real or mocked databases
- Error Handling Tests: Verify appropriate HTTP status codes (400, 401, 404, 500) and error responses
- Performance Tests: Measure response times and test under load
- Security Tests: Test authentication, authorization, and input validation
- Backward Compatibility Tests: Ensure updates don’t break existing clients
- Automated Tests: Simulate requests, measure execution speed, validate responses
35. Explain the difference between REST APIs and other architectural styles like RPC or SOAP.
REST differs from other approaches:
- REST APIs: Resource-oriented, stateless, uses HTTP verbs, supports multiple data formats, ideal for web services, easy to develop and maintain, lower bandwidth usage
- RPC (Remote Procedure Call): Function-oriented, calls remote functions as if local, typically uses XML or JSON, less standardized than REST
- SOAP: Highly structured, XML-based, supports complex operations and transactions, higher security, more overhead, better for enterprise applications requiring advanced features
REST is preferred for most modern web applications due to simplicity, scalability, and broad browser support. SOAP is better for high-security scenarios or complex transaction requirements.
36. How would you document a REST API for developers?
Comprehensive API documentation should include:
- OpenAPI/Swagger Specification: Machine-readable contract defining all endpoints, parameters, and responses
- Getting Started Guide: Quick tutorial for making the first API call in under 5 minutes
- Authentication Guide: How to obtain and use credentials (API keys, tokens, OAuth)
- Endpoint Reference: Detailed documentation for each endpoint with examples
- Error Reference: All possible error codes and how to handle them
- Rate Limit Documentation: Limits per tier and how to handle 429 responses
- Changelog: What changed in each version
- Code Examples: Sample requests and responses in multiple programming languages
37. Design a REST API for a multi-tenant SaaS application where each tenant has isolated data.
Multi-tenant architecture requires careful design:
- Tenant Isolation: Extract tenant ID from authentication token or subdomain
- Endpoints: /api/v1/tenants/{tenantId}/resources or implicit tenant from auth context
- Database Design: Separate schemas per tenant or row-level security with tenant column
- Query Filtering: All queries automatically filtered to tenant’s data
- Authentication: Verify token includes authorized tenant IDs
- Audit Logging: Track which tenant accessed what data and when
This ensures data privacy, prevents cross-tenant data leakage, and allows independent customization per tenant.
Conclusion
REST API interview questions cover a broad spectrum from fundamental HTTP concepts to sophisticated architectural patterns. Success in REST API interviews requires understanding not just the technical mechanics but also best practices for design, security, performance, and maintainability. Focus on practical examples, real-world scenarios, and the reasoning behind design decisions. Remember that interviewers value the ability to think through tradeoffs and explain your decisions clearly, not just reciting specifications. Practice implementing REST APIs, experimenting with different design approaches, and staying current with industry best practices as you prepare for your interview.