Blog
Restful API mostly asked interview questions
- February 5, 2026
- Posted by: InterviewExpert.org
- Category: Backend Interview Preparation Rest Api
REST & HTTP Fundamentals
1. What is REST and what are its architectural principles?
REST (Representational State Transfer) is an architectural style for designing scalable, stateless web services that communicate over HTTP.
Key REST principles:
- Code on demand (optional)
- Client–Server separation
- Stateless communication
- Uniform interface
- Cacheability
- Layered system
2. What are RESTful web services?
RESTful web services are web services that follow the principles of REST (Representational State Transfer) to enable simple, scalable, and stateless communication between client and server over HTTP.
They expose resources (data or functionality) through URLs and use standard HTTP methods like GET, POST, PUT, PATCH, and DELETE to perform operations on those resources.
3. How does REST differ from SOAP?
REST is a lightweight architectural style that uses HTTP and usually JSON, making it fast and scalable, while SOAP is a strict XML-based protocol with built-in security and standards, mainly used in enterprise systems.
REST is better for performance and scalability, while SOAP is better for strict security and transactions.
4. What are the main HTTP methods used in REST?
REST mainly uses HTTP methods like GET, POST, PUT, DELETE, PATCH, and OPTIONS to perform operations on resources. GET fetches data, POST creates, PUT replaces, PATCH partially updates, DELETE removes resources, and OPTIONS checks supported operations.
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create data |
| PUT | Replace data |
| PATCH | Partial update |
| DELETE | Delete data |
| OPTIONS | Check supported methods |
5. What is a resource in RESTful APIs?
In RESTful APIs, a resource is any piece of data or object that can be identified by a unique URI and manipulated using HTTP methods.
Easy Examples of Resources
- User
- Order
- Product
- Payment
6. Explain statelessness in REST APIs.
In REST, each request contains all required information. The server does not store client session state, improving scalability and reliability.
7. What is a URI and how is it used in REST?
A URI (Uniform Resource Identifier) uniquely identifies a resource.
Example:
GET /api/orders/500URIs represent nouns, not actions.
8. What does CRUD stand for and how does it map to REST methods?
| CRUD | HTTP Method |
|---|---|
| Create | POST |
| Read | GET |
| Update | PUT / PATCH |
| Delete | DELETE |
9. What are safe and idempotent HTTP methods?
Safe methods never modify data, while idempotent methods can modify data but produce the same result when called multiple times. GET is safe because it never modifies data, and idempotent because multiple calls produce the same result.
Safe methods: Do not modify data
- GET, HEAD, OPTIONS
Idempotent methods: Same result on repeated calls
- GET, PUT, DELETE
Example: Multiple DELETE calls → resource still deleted.
10. What are common HTTP status codes used in RESTful APIs and their meanings?
Most Common Status Codes (Must-Know)
2xx – Success
- 200 OK → Request successful
- 201 Created → Resource created successfully
- 204 No Content → Success, but no response body
4xx – Client Errors
- 400 Bad Request → Invalid request data
- 401 Unauthorized → Authentication required
- 403 Forbidden → Access denied
- 404 Not Found → Resource not found
- 409 Conflict → Duplicate or conflicting request
5xx – Server Errors
- 503 Service Unavailable → Server temporarily unavailable
- 500 Internal Server Error → Generic server failure
- 502 Bad Gateway → Invalid response from upstream server
REST Architecture & Concepts
1. What are REST constraints (uniform interface, cache-ability, layer system)?
Uniform Interface: Standard way to interact with resources using HTTP methods, URIs, headers, and status codes, improves simplicity and interoperability.
Cache-ability: Responses must define whether they are cacheable to improve performance and reduce server load.
Layered System: Client does not know whether it is communicating directly with the server or an intermediary (proxy, gateway), improving scalability and security.
2. What is HATEOAS? Explain its importance.
HATEOAS (Hypermedia As The Engine Of Application State) means the API response includes links to related actions/resources.
Importance:
- Enables easier evolution of APIs without breaking clients
- Reduces client–server coupling
- Makes APIs self-discoverable
3. What is idempotency and why is it important?
A request is idempotent if multiple identical requests produce the same result.
Example:
- POST → not idempotent
- PUT, DELETE → idempotent
4. What is content negotiation?
Content negotiation allows the client and server to agree on the response format.
- Client uses
Acceptheader - Server responds with supported format (JSON, XML)
Example:
Accept: application/json5. How is versioning handled in REST APIs?
Common strategies:
- URI versioning:
/api/v1/users - Header versioning:
Accept: application/vnd.app.v1+json - Query parameter:
/users?version=1
URI versioning is the most commonly used and simplest.
6. What is caching and how can it be implemented in REST?
Caching stores responses to avoid repeated processing.
Implementation:
- Client-side, proxy, or CDN caching
- HTTP headers:
Cache-Control,Expires - Conditional requests using
ETagandIf-None-Match
7. Explain the difference between PUT vs PATCH.
| PUT | PATCH |
|---|---|
| Replaces entire resource | Updates partial resource |
| Idempotent | Usually idempotent |
| Requires full object | Sends only changed fields |
8. What is pagination and how do you implement it?
Pagination divides large datasets into smaller chunks.
Implementation methods:
- Cursor-based pagination for large datasets
- Query parameters:
?page=1&size=10 - Offset-limit:
?offset=20&limit=10
9. What are ETags and how do they help with caching?
ETags (Entity Tags) are unique identifiers for a resource version that help browsers and clients cache responses and avoid downloading unchanged data. ETags allow clients to cache responses efficiently by validating whether a resource has changed before fetching it again.
10. What is API version depreciation strategy?
An API version deprecation strategy is a planned approach to retire old API versions safely while giving clients time to migrate to newer versions without breaking their applications. API version deprecation ensures backward compatibility while smoothly transitioning clients to newer versions.
Design & Best Practices
1. What are REST API design best practices?
Key best practices include:
- Use nouns for resources (
/users,/orders) - Follow HTTP methods semantics correctly (GET, POST, PUT, DELETE)
- Return proper HTTP status codes
- Make APIs stateless
- Support pagination, filtering, sorting
- Use versioning for breaking changes
- Provide consistent error responses
- Secure APIs using OAuth2 / JWT
- Document APIs clearly
These practices improve maintainability, scalability, and developer experience.
2. How do you choose resource naming conventions?
- Use plural nouns for collections (
/users) - Avoid verbs (
/createUser ❌) - Use hierarchical relationships where needed:
/users/{userId}/orders- Use kebab-case or lowercase consistently
- Avoid implementation details in URIs
3. What is API documentation and how is it maintained?
API documentation is a guide that explains how to use an API, including its endpoints, request/response formats, parameters, and error codes. API documentation is maintained by updating it whenever the API changes.
What API Documentation Contains
- API endpoints (URLs)
- HTTP methods (GET, POST, etc.)
- Request parameters & headers
- Request/response examples
- Status codes & error messages
- Authentication details
4. What are common patterns for API error responses?
Common API error response patterns provide a consistent JSON structure with an error code, message, and details so clients can easily understand and handle failures.
Most Common Error Response Patterns
1. Standard JSON Error Object (Most Used)
{
"timestamp": "2026-02-10T10:30:00Z",
"status": 400,
"error": "Bad Request",
"message": "Invalid email format",
"path": "/api/users"
}✔ Easy to read
✔ Widely used in REST APIs
2. Error Code + Message Pattern
{
"errorCode": "USER_001",
"errorMessage": "User not found"
}✔ Machine-friendly
✔ Easy for frontend mapping
3. Validation Error Pattern
{
"errors": [
{
"field": "email",
"message": "Email is invalid"
}
]
}✔ Best for form validations
✔ Clear field-level errors
4. RFC 7807 – Problem Details (Standard)
{
"type": "https://example.com/errors/invalid-input",
"title": "Invalid input",
"status": 400,
"detail": "Email format is incorrect"
}✔ Standardized
✔ Used in modern APIs
5. How do you handle API deprecation?
API deprecation is the process of phasing out an old API version without breaking existing clients.
Best practices to handle API deprecation:
- Gradually remove deprecated APIs
After the sunset period, remove the old version safely. - Announce deprecation early
Clearly mark the API as deprecated in documentation and communicate timelines to consumers. - Version your APIs
Introduce breaking changes in a new version (e.g.,/api/v2) while keeping/api/v1operational. - Use deprecation headers
Include HTTP headers like:Deprecation: true Sunset: Wed, 30 Jun 2026 23:59:59 GMTto inform clients programmatically. - Maintain backward compatibility temporarily
Continue supporting the old version for a defined grace period. - Provide migration guides
Document changes and offer examples to help clients upgrade smoothly. - Monitor deprecated API usage
Log and track which clients still use deprecated endpoints.
6. How does an API gateway work? (high-level)
An API Gateway acts as a single entry point between clients and backend services (usually microservices).
High-level working flow:
High-level working flow:
- Client sends request
The client (web, mobile, third-party app) sends all API requests to the API Gateway instead of directly to services. - Request validation & security
The gateway handles:- Authentication (JWT, OAuth2, API keys)
- Authorization
- SSL termination
- Traffic control
It applies:- Rate limiting & throttling
- Request size limits
- IP filtering
- Routing & load balancing
The gateway forwards the request to the appropriate backend service and may load-balance across multiple instances. - Cross-cutting concerns
Centralized handling of:- Logging and monitoring
- Caching
- Request/response transformation
- Response aggregation (optional)
Combines responses from multiple microservices into a single response for the client. - Response sent back to client
The gateway returns the final response to the client.
7. What is API throttling?
API throttling is a technique used to limit the number of requests a client can make to an API within a specified time window.
Why API throttling is needed
- Prevents API abuse and DDoS attacks
- Protects backend services from overload
- Ensures fair usage among clients
- Improves overall system stability and performance
How API throttling works (high level)
- Client sends requests to the API
- Throttling rules are checked (per user, IP, API key)
- If the limit is exceeded:
- Request is rejected with HTTP 429 (Too Many Requests)
- If within limit:
- Request is forwarded to the backend service
8. How do you design for backward compatibility?
Key principles for designing backward-compatible APIs
- Never break existing contracts
Do not remove or rename existing fields, endpoints, or status codes. - Additive changes only
- Add new fields instead of modifying old ones
- Ensure new fields are optional
- Provide default values
- Preserve response formats
Keep existing JSON structure intact and avoid changing data types. - Use API versioning for breaking changes
Introduce/v2for incompatible changes while maintaining/v1. - Tolerant readers
Design clients to ignore unknown fields in responses. - Maintain semantic consistency
Avoid changing the meaning of existing fields or behavior. - Deprecate gracefully
Mark features as deprecated and provide migration paths before removal.
Error Handling & Testing
1. How do you implement error handling in RESTful APIs?
Error handling in RESTful APIs is implemented by returning appropriate HTTP status codes along with a clear and consistent error response body, and by centralizing exception handling.
Key steps to implement error handling
- Use correct HTTP status codes
400 Bad Request– Invalid input / validation error401 Unauthorized– Authentication required403 Forbidden– Access denied404 Not Found– Resource not found500 Internal Server Error– Server failure
- Define a standard error response structure
Return a predictable JSON format so clients can easily parse errors:
{ "timestamp": "2026-02-10T12:30:00", "status": 400, "error": "Bad Request", "message": "Invalid email format", "path": "/api/users" }- Centralize exception handling
Handle all exceptions in one place instead of per controller.- In Spring Boot, use
@ControllerAdvicewith@ExceptionHandler
- In Spring Boot, use
- Handle validation errors explicitly
Return meaningful messages for field-level validation failures. - Avoid exposing internal details
Do not leak stack traces or sensitive system information in responses. - Log errors properly
Log technical details on the server while returning user-friendly messages to clients.
2. How do you test REST APIs? (tools & methods)
Testing REST APIs ensures that the APIs are correct, reliable, secure, and scalable. It is usually done at multiple levels using different tools.
Testing methods
1. Unit Testing
- Tests individual components like controllers and services in isolation
- Focuses on request handling, validation, and response structure
Tools:
- JUnit
- Mockito
- Spring
@WebMvcTest,MockMvc
2. Integration Testing
- Tests API behavior with real dependencies (database, message queues, security)
- Verifies request-to-response flow
Tools:
- Spring Boot
@SpringBootTest - REST Assured
- Testcontainers
3. End-to-End (E2E) Testing
- Tests the complete system as a client would use it
- Covers authentication, authorization, and data flow
Tools:
- Postman
- Newman
- Curl
4. Contract Testing
- Ensures API implementation matches the agreed contract between services
- Prevents breaking changes
Tools:
- Spring Cloud Contract
- Pact
5. Performance & Load Testing
- Validates API behavior under high traffic
- Measures response time and throughput
Tools:
- JMeter
- Gatling
- k6
- Locust
Common testing tools
- Postman – Manual testing and automation
- Swagger UI (OpenAPI) – Interactive testing + documentation
- REST Assured – Java-based API testing
- Curl – Quick command-line testing
3. How do you use Postman/Swagger for testing and documentation?
Postman and Swagger are commonly used together, Swagger for documentation and exploration, and Postman for testing and automation.
Using Swagger (OpenAPI)
Purpose: API documentation + interactive testing
How it is used:
- Define APIs using OpenAPI specification
- Automatically generate interactive documentation
- Test APIs directly from the browser
- Keeps documentation in sync with code
What it documents:
- Endpoints and HTTP methods
- Request/response models
- Status codes
- Authentication methods
Benefit:
Provides a single source of truth for API consumers.
Using Postman
Purpose: Manual and automated API testing
How it is used:
- Send HTTP requests (GET, POST, PUT, DELETE)
- Validate responses, headers, and status codes
- Write test scripts using JavaScript
- Organize APIs into collections
- Automate tests using Newman (CLI)
Benefit:
Helps in functional, regression, and integration testing.
4. What are mock servers and how are they used?
A mock server is a simulated server that mimics the behavior of a real API by returning predefined responses without calling the actual backend.
Why mock servers are used
Mock servers are mainly used when:
- Backend APIs are not ready yet
- Third-party APIs are unavailable, slow, or costly
- Teams want to test edge cases and failures
- Frontend and backend teams work independently
How mock servers work (high-level)
- Client sends a request to the mock server
- Mock server matches the request (URL, method, headers)
- Returns a predefined response (JSON, status code, headers)
- No real business logic or database is involved
Popular mock server tools
- Postman Mock Servers
- WireMock (very common in Spring Boot testing)
- MockServer
- JSON Server (lightweight)
5. What is load testing in the context of REST APIs?
Load testing is the process of evaluating how a REST API performs under expected and peak traffic conditions by sending a large number of concurrent requests.
Why load testing is important
- Ensures the API can handle real-world traffic
- Identifies performance bottlenecks (CPU, memory, DB, network)
- Validates scalability and stability
- Prevents production outages
Common load testing tools
- JMeter
- Gatling
- k6
- Locust
Types of performance testing
- Load testing – Expected traffic
- Stress testing – Beyond capacity
- Spike testing – Sudden traffic surge
- Soak testing – Long-duration load