REST WebServiceQA
REST WebServiceQA
Let’s go step by step, part by part, and I’ll provide detailed answers
with examples where applicable.
2. How does REST differ from RPC or SOAP in terms of architectural style?
Heavy WS-*
Lightweight and Tight coupling to
Flexibility standards, tight
loosely coupled method signatures
coupling
Example:
- REST: GET /customers/123 - RPC: getCustomer(123)
Example:
Domain: E-commerce
Resources: Customer, Order, Product
URIs:
- /customers
- /customers/{id}/orders
- /products
Each resource should be addressable, and operations should be carried out via
HTTP methods: - GET /products/101 → Fetch product - POST /orders → Create new order
4. What are the constraints of REST and why are they important?
Ignoring these constraints often leads to tightly coupled systems and scalability
bottlenecks.
Example:
Client
Simplicity More calls, client assembles One call, less client work
More latency (multiple Better performance for UI
Performance
requests) needs
10. How would you handle versioning in REST APIs? What are the pros and
cons of each approach?
Harder for
Header Accept:
Clean URIs caching,
versioning application/vnd.orders.v1+json
discovery
Complex
Content
Accept headers Flexible client-side
negotiation
handling
Best practice: Use URI versioning for public APIs; use header-based for internal
APIs when needed.
PART 2: API Design Best Practices
12. How do you handle pagination, filtering, and sorting in REST APIs?
GET /products?page=2&limit=20
Response:
{
"data": [...],
"pagination": {
"page": 2,
"limit": 20,
"total": 300,
"pages": 15
}
}
Filtering:
GET /products?category=books&price_lt=50
Sorting:
GET /products?sort=price,-rating
13. What conventions do you follow for naming endpoints and resources?
14. What are common REST anti-patterns you’ve seen, and how do you avoid
them?
Using only POST for all operations Use correct HTTP verbs
15. How do you ensure consistency in API response formats across large
systems?
{
"data": {...},
"errors": [],
"meta": {...}
}
16. When would you use HTTP methods like PATCH vs PUT?
Example:
PUT /users/123
{
"name": "Alice",
"email": "[email protected]"
}
PATCH /users/123
{
"email": "[email protected]"
}
Best Practice: Prefer PATCH when updating partial fields to reduce data transfer
and avoid accidental overwrites.
{
"id": 123,
"name": "Alice",
"_links": {
"self": { "href": "/users/123" },
"orders": { "href": "/users/123/orders" }
}
}
Reality: Often avoided in modern REST due to complexity; simple clients prefer static
contracts.
PATCH /users/123
Content-Type: application/merge-patch+json
{
"email": "[email protected]"
}
Uploads:
Use multipart/form-data
Support pre-signed URLs with object stores (S3-style):
1. Client requests upload URL
2. Server returns secure URL
3. Client uploads directly
Downloads:
Use streaming APIs
Set Content-Disposition: attachment for downloading files
Best Practice: - Automate API docs generation from annotations (e.g., SpringDoc for
Java). - Version API docs along with API itself.
Tech stack examples: - OAuth2/JWT for auth - HTTPS for transport - OWASP Top 10
mitigation - Identity federation (SSO, LDAP integration)
22. What are common security risks in REST and how do you mitigate them?
Input validation,
Injection (SQL, JSON, etc.)
parameterized queries
Implement RBAC/ABAC
Broken Object Level Authorization
properly
Example:
JWT payload:
{
"sub": "user123",
"roles": ["admin"]
}
Flows: - Authorization Code Flow – Most secure (for web/mobile apps). - Client
Credentials Flow – For machine-to-machine APIs. - Implicit Flow – Deprecated
(used in old SPAs). - Device Flow – For devices like TVs.
25. How would you design REST APIs to prevent injection and CSRF attacks?
Injection Prevention:
Validate all input (use schemas)
Sanitize inputs (XSS protection)
Use prepared statements
CSRF (less common in REST):
Use stateless APIs (no session cookies)
Use JWT or custom headers (CSRF-safe)
Same-origin policies + SameSite cookies if applicable
26. What is your approach to securing sensitive data in transit and at rest?
In Transit:
Enforce HTTPS (TLS 1.2 or 1.3)
Reject HTTP (redirect or block)
Secure headers: Strict-Transport-Security, X-Frame-Options
At Rest:
Encrypt databases (AES-256)
Tokenize/Pseudonymize PII
Encrypt secrets and credentials using vaults (e.g., HashiCorp Vault, AWS
KMS)
27. How do you make REST APIs scalable in large enterprise environments?
Architecture example:
Example:
Client sends:
If-None-Match: "abc123"
29. How do you deal with rate limiting and throttling in REST APIs?
Rate Limiting: Controls how many requests a client can make in a time
window.
Throttling: Slows down requests after a threshold is hit instead of blocking.
Implement via API Gateway: - Per API key or user/IP - Sliding window or token
bucket algorithm - Response headers:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 250
X-RateLimit-Reset: 1671602933
32. What is your experience with asynchronous REST APIs and when do you
use them?
Approaches: - Callback mechanism: - Client receives task ID, polls or waits for
webhook - Polling: - GET /tasks/{id}/status - Webhooks: - Notify client when work is
done
A good API should provide clear, consistent, and actionable error responses.
Standard structure:
{
"error": {
"code": "USER_NOT_FOUND",
"message": "User with ID 123 not found",
"details": "The user may have been deleted or the ID is invalid"
}
}
34. How do you structure error responses (e.g., status codes, custom error
objects)?
Typical pattern:
{
"timestamp": "2025-03-20T10:00:00Z",
"status": 404,
"error": "Not Found",
"code": "RESOURCE_NOT_FOUND",
"message": "User not found",
"path": "/users/123"
}
Use HTTP status codes for protocol-level error handling: - 200 OK, 201 Created, 204 No
Content - 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found - 500 Internal
Server Error
Use business-specific error codes inside the payload for client-specific logic.
Example:
37. What tools do you use for observability, logging, tracing, and alerting in
RESTful systems?
POST /payments
→ Internally calls:
GET /customers/{id}
41. Have you used API gateways? What are their benefits and design
considerations?
Yes — API Gateways (e.g., Kong, Apigee, AWS API Gateway, NGINX) act as a
proxy layer between clients and services.
Techniques: - Additive changes only (add fields, don’t remove or rename) - API
versioning (e.g., /v1/products) - Graceful deprecation policy - Mark endpoints as
deprecated - Monitor usage metrics before removal - Use feature flags for
introducing behavioral changes - Contract testing to validate impact on consumers
Stages of the API lifecycle: 1. Design – Use OpenAPI/Swagger, align with business
requirements. 2. Development – Version-controlled code and spec. 3. Testing – Unit,
integration, contract, performance testing. 4. Deployment – Through CI/CD
pipelines. 5. Monitoring & Support – API metrics, logging, incident management. 6.
Deprecation – Notify consumers, monitor usage, gradually sunset old versions.
Best Practices: - Use API gateways to support multiple versions. - Provide API
changelogs and migration guides. - Tag endpoints as deprecated in OpenAPI docs
before removal.
A well-structured CI/CD pipeline automates build, test, and deployment of REST APIs.
Typical steps in pipeline: 1. Build: Compile and run linters, static code analysis. 2.
Unit tests: Verify logic. 3. Contract testing: Ensure compatibility with consumers.
4. Integration tests: Test APIs with dependent systems. 5. Security scans: (e.g.,
OWASP checks, Snyk, Checkmarx) 6. Generate artifacts: API spec, Docker images.
7. Deploy to staging → run smoke tests → promote to production
Tools: Jenkins, GitHub Actions, GitLab CI, Azure DevOps, ArgoCD
46. How do you test REST APIs at unit, integration, and contract levels?
47. How do you align REST API design with business domain modeling
(DDD)?
49. What metrics do you track to measure REST API adoption and success?
Type Examples
Tools: API analytics platforms (Apigee, Kong, Postman Monitoring, New Relic)
50. How do you manage API governance and standardization across teams in
a large organization?
Maturity model helps teams grow from ad-hoc design to well-governed practices.
Mock Interview Scenario 1: API Gateway Design in a Multi-
Region Setup
Questions: - How do you break down the monolith into microservices from
a REST perspective? - How do you handle shared database access during
transition? - How will REST API contracts be maintained to avoid client
breakage? - What strategy would you use to ensure backward compatibility?
Context: Your company wants to expose a public REST API to enable third-
party developers to build integrations. You’ll lead API design, security, and
developer enablement.
Context: Multiple teams are consuming a shared REST API that’s about to
change. You need to manage these changes without breaking downstream
services.
Context: Your REST APIs are now live and critical to business operations.
The leadership wants better observability, including performance metrics,
error trends, and API usage analytics.
Questions: - What are the key metrics you would track for REST APIs? -
What tooling and architecture would you recommend? - How do you ensure
traceability across distributed microservices? - How do you proactively
detect and respond to issues?
Context: Your frontend teams are pushing for more flexibility in fetching
data. They are requesting a shift from REST to GraphQL for better query
control and reduced over-fetching.
1. Transition Strategy:
Start by introducing GraphQL alongside REST, not replacing it
immediately (dual-stack approach).
Identify read-heavy, complex resource-fetching use cases as good
GraphQL candidates.
Wrap existing REST endpoints in a GraphQL abstraction layer (e.g.,
Apollo Gateway) if needed.
2. Trade-offs Between REST and GraphQL:
Pros of GraphQL:
Precise querying, avoids over-fetching
Single round-trip for nested resources
Better for frontend agility
Cons:
Complexity in server schema and resolver design
More challenging caching and observability
No built-in HTTP status codes (error handling needs custom design)
3. Auth, Versioning, and Caching in GraphQL:
Authentication: Still done via HTTP headers (OAuth2, JWT)
Authorization: Must be handled at field-level or resolver-level in code
Versioning: Avoid versioning GraphQL APIs; use schema evolution
instead (add-only changes)
Caching: Use Apollo Client cache, or persisted queries with CDN
support
4. Balancing REST and GraphQL:
Maintain REST for simpler or legacy clients
Let frontend teams gradually migrate features to GraphQL
Expose analytics for adoption tracking
Eventually retire REST endpoints once GraphQL coverage is sufficient