Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Sunday, September 7, 2025

Mastering REST APIs: Top 150+ Interview Questions for Beginners, Intermediate, and Experts in 2025

 

Beginner Level: Building Basic Understanding and IQ Fundamentals

Beginner questions focus on core concepts, simple definitions, and IQ-style puzzles to test foundational knowledge. These are ideal for entry-level roles or freshers, emphasizing basic understanding with example data.

  1. What is a REST API, and how does it differ from a general Web API? A REST API is an architectural style for designing networked applications using HTTP requests to access and manipulate data. It differs from a general Web API (which could use SOAP or GraphQL) by being stateless, cacheable, and using standard HTTP methods like GET, POST. Example: A REST API for a blog might use GET /posts to fetch articles, while a Web API could involve XML-based SOAP for enterprise integrations. Analytical insight: REST promotes simplicity and scalability, making it ideal for mobile apps.
  2. Explain the key principles of REST architecture. REST principles include statelessness (no client context stored on server), cacheability (responses can be cached), uniform interface (standard methods), and layered system. Example: In a e-commerce API, statelessness means each request to /cart must include authentication tokens. IQ test: Why is statelessness beneficial? It enhances scalability by allowing load balancing without session stickiness.
  3. What are the main HTTP methods used in REST APIs? GET (retrieve data), POST (create data), PUT (update data), DELETE (remove data), PATCH (partial update). Example data: GET /users/1 returns {"id":1, "name":"John"}. Basic understanding: GET is idempotent and safe, unlike POST which creates new resources.
  4. What is an endpoint in a REST API? An endpoint is a specific URL path where an API service is available, like /users or /products/123. Example: In a weather app, GET /weather?city=London fetches data. IQ puzzle: Design an endpoint for user login – typically POST /auth/login with body {"username":"user", "password":"pass"}.
  5. Define idempotency in REST APIs. An operation is idempotent if repeating it yields the same result, like PUT or DELETE. Example: PUT /users/1 {"name":"Alice"} updates once; repeating doesn't change further. Analytical: Non-idempotent POST can create duplicates if retried, causing issues in payment systems.
  6. What is the role of HTTP status codes in REST? Status codes indicate response outcomes: 200 OK (success), 404 Not Found (resource missing), 500 Internal Server Error. Example: On failed login, return 401 Unauthorized. Basic IQ: Why use 201 Created for POST? It signals new resource creation with location header.
  7. Explain URI vs. URL in API context. URI (Uniform Resource Identifier) identifies a resource abstractly; URL (Locator) specifies location. Example: URI: users/1; URL: https://api.example.com/users/1. Understanding: URIs enable hypermedia in REST (HATEOAS).
  8. What is JSON, and why is it preferred in REST APIs? JSON (JavaScript Object Notation) is a lightweight data format. Preferred for readability and parsing ease over XML. Example data: {"product":{"id":1,"price":99.99}}. IQ: Convert XML <user><name>John</name></user> to JSON – {"user":{"name":"John"}}.
  9. Describe stateless vs. stateful APIs. Stateless: Each request is independent; stateful: Server remembers client state. REST is stateless. Real-life: Stateless APIs scale better in cloud environments like AWS Lambda.
  10. What is API versioning, and why is it important? Versioning prevents breaking changes, e.g., via URL (/v1/users) or headers. Example: v1 returns basic user data; v2 adds email. Basic: Avoids disrupting existing clients.
  11. Explain the difference between GET and POST. GET retrieves data (query params); POST submits data (body). Example: GET /search?q=book; POST /books with {"title":"API Guide"}. IQ: Why not use GET for sensitive data? It logs in URLs.
  12. What are query parameters in REST? Key-value pairs in URL after ?, like /users?age=25&sort=asc. Example data: Filters users over 25 years old.
  13. Define resource in REST terms. A resource is any data entity, like user or post, accessed via URIs. Example: /orders/456 represents an order resource.
  14. What is HATEOAS in REST? Hypermedia as the Engine of Application State: Responses include links to related actions. Example: GET /users/1 returns {"name":"John", "links":[{"rel":"posts","href":"/users/1/posts"}]}.
  15. Explain safe vs. unsafe HTTP methods. Safe: No side effects (GET, HEAD); Unsafe: Modify resources (POST, PUT). Analytical: Safe methods are cacheable.
  16. What is CORS, and why is it needed? Cross-Origin Resource Sharing allows restricted resources on a web page from another domain. Example: API at api.example.com allows requests from www.client.com via headers.
  17. Describe API authentication basics. Methods like API keys, Basic Auth. Example: Header Authorization: Basic base64(username:password).
  18. What is rate limiting in APIs? Limits requests per time window to prevent abuse. Example: 100 requests/hour per IP.
  19. Explain content negotiation. Client requests format via Accept header; server responds accordingly. Example: Accept: application/json returns JSON.
  20. What are headers in HTTP requests? Metadata like Content-Type: application/json. Example: User-Agent for client info.
  21. Define payload in API context. Data sent in request/response body. Example: POST payload {"email":"user@example.com"}.
  22. What is API documentation? Guides like Swagger/OpenAPI for endpoints. Basic: Ensures usability.
  23. Explain synchronous vs. asynchronous APIs. Sync: Immediate response; Async: Callback or polling. REST is typically sync.
  24. What is caching in REST? Store responses for faster access using Cache-Control headers. Example: Cache-Control: max-age=3600.
  25. Describe error handling basics. Use status codes and error bodies like {"error":"Invalid input"}.
  26. What is OAuth for APIs? Delegation protocol for access without passwords. Example: Google login for apps.
  27. Explain path parameters. Variables in URL like /users/{id}. Example: /users/5 fetches user 5.
  28. What is hypermedia? Links in responses guiding navigation. Example in HATEOAS.
  29. Define API gateway. Entry point for managing APIs. Basic: Handles routing, auth.
  30. What are webhooks? Server-to-client callbacks. Example: GitHub push notifications.
  31. Explain REST vs. SOAP. REST: Lightweight, HTTP; SOAP: Protocol with XML. Analytical: REST better for web.
  32. What is XML in APIs? Alternative to JSON. Example: <user><id>1</id></user>.
  33. Describe request body. Data in POST/PUT. Example: JSON object.
  34. What is response time in APIs? Latency from request to response. Basic: Optimize for user experience.
  35. Explain idempotent methods again with example. PUT /items/1 {"qty":10} – repeating sets to 10. IQ: Useful for retries.
  36. What are status code ranges? 1xx info, 2xx success, 3xx redirect, 4xx client error, 5xx server.
  37. Define client-server architecture in REST. Separation of concerns: Client requests, server responds.
  38. What is uniform interface? Standard ways to interact with resources.
  39. Explain layered system principle. Intermediaries like proxies without affecting client/server.
  40. What is code on demand? Optional: Server sends executable code. Rare in REST.
  41. Describe basic API testing. Use Postman for GET/POST. Example: Test 200 OK on /health.
  42. What is API mocking? Simulate APIs for development. Example: Mock server returns fake data.
  43. Explain API keys. Unique identifiers for auth. Example: Header X-API-Key: abc123.
  44. What is Bearer token? JWT in Authorization: Bearer <token>.</token>
  45. Define throttling. Synonym for rate limiting.
  46. What is pagination? Split large responses, e.g., ?page=1&limit=10.
  47. Explain filtering in APIs. Query params like ?status=active.
  48. What is sorting? ?sort=desc on field.
  49. Describe search in REST. GET /search?q=term.
  50. What is validation in APIs? Check input data. Example: Ensure email format.

Intermediate Level: Scenario-Based, Real-Life Centric, and Example Data-Oriented

Intermediate questions delve into practical scenarios, data handling, and analytical problem-solving for mid-level roles.

  1. Scenario: Design a REST API for a todo list app. What endpoints would you create? Endpoints: GET /todos, POST /todos, GET /todos/{id}, PUT /todos/{id}, DELETE /todos/{id}. Example data: POST {"task":"Buy milk","done":false} returns 201 with ID. Real-life: Handle user auth for personal todos.
  2. How would you handle versioning in a production API without breaking clients? Use URL versioning (/v2/users) or header (Accept: application/vnd.example.v2+json). Scenario: Migrate from v1 (basic fields) to v2 (added phone). Analytical: Header versioning keeps URLs clean but requires client support.
  3. Explain authentication with JWT in REST APIs. JSON Web Tokens: Client logs in, gets token, sends in headers. Example: Decode token {"sub":"user1","exp":1694000000}. Real-life: Secure microservices communication.
  4. Scenario: A client complains of slow API responses. How do you diagnose and optimize? Check logs, use profiling tools. Optimize with caching, database indexes. Example: Add Redis cache for GET /products. Analytical: Reduce N+1 queries in ORM.
  5. What is the difference between PUT and PATCH? Provide a coding example. PUT replaces entire resource; PATCH partial update. Example (JSON): PUT /users/1 {"name":"Bob","age":30}; PATCH /users/1 {"age":31}. Scenario: Use PATCH for bandwidth efficiency in mobile apps.
  6. How do you implement rate limiting in a REST API? Use middleware like Redis counters. Example: Limit 5 req/min per IP; return 429 Too Many Requests if exceeded. Real-life: Prevent DDoS in public APIs.
  7. Scenario: Design an API for file uploads. What considerations? POST /uploads with multipart/form-data. Handle large files with streaming. Example: Response {"fileUrl":"https://storage/file.jpg"}. Analytical: Secure against malicious uploads.
  8. Explain error handling with custom responses. Standardize {"status":400,"message":"Invalid param","details":{}}. Scenario: Validate inputs server-side.
  9. How does CORS work in practice? Provide code example. Server sets Access-Control-Allow-Origin: . Example (Node.js): res.header("Access-Control-Allow-Origin", ""). Real-life: Enable for frontend-backend separation.
  10. Scenario: Implement pagination for a large dataset. Use offset/limit or cursor-based. Example: GET /posts?page=2&limit=20 returns links to next/prev. Analytical: Cursor better for infinite scrolling.
  11. What is API composition, and when to use it? Aggregate multiple APIs into one endpoint. Example: /user-profile combines /users and /posts. Scenario: Reduce client requests in dashboards.
  12. Explain OAuth 2.0 flows with examples. Authorization Code for web apps; Client Credentials for server-to-server. Example: Redirect to /auth?client_id=abc&scope=read.
  13. Scenario: Handle concurrent updates in REST. Use optimistic locking with ETag headers. Example: If-Match: "etag-value" on PUT; 412 if mismatch. Real-life: Prevent lost updates in collaborative tools.
  14. How to secure sensitive data in APIs? Use HTTPS, encrypt payloads. Example: Never log passwords. Analytical: Comply with GDPR.
  15. What is content negotiation with Accept headers? Client: Accept: application/xml; Server responds in XML if supported. Scenario: Support multiple formats.
  16. Scenario: Design a search API with filters. GET /products?category=electronics&price_min=100&sort=price_asc. Example data: Returns paginated list.
  17. Explain webhooks vs. polling. Webhooks: Push notifications; Polling: Client checks periodically. Example: Webhook POST /callback on event.
  18. How to implement caching strategies? Use ETag for validation, Cache-Control for expiration. Scenario: Cache static data like configs.
  19. Scenario: API for real-time updates – is REST suitable? REST is stateless; use WebSockets for real-time. But combine: REST for init, WS for updates. Analytical: Chat apps need WS.
  20. What are common API design anti-patterns? Using POST for everything, poor naming. Example: Avoid /doAction?type=get.
  21. Explain HATEOAS with a full example. Response: {"data":{...}, "links":[{"rel":"self","href":"/item/1"},{"rel":"delete","href":"/item/1","method":"DELETE"}]}. Scenario: Self-discoverable APIs.
  22. Scenario: Handle large request bodies. Set limits, use compression. Example: Accept-Encoding: gzip.
  23. How to monitor API performance? Use tools like Prometheus. Track metrics: latency, error rates.
  24. Explain API keys vs. tokens. Keys: Static; Tokens: Time-limited. Example: Tokens for sessions.
  25. Scenario: Design a payment API. POST /payments with idempotency key. Return 202 Accepted for async processing.
  26. What is schema validation? Use JSON Schema. Example: Validate {"type":"object","properties":{"name":{"type":"string"}}}.
  27. Explain batch operations in REST. POST /batch with array of requests. Scenario: Bulk updates.
  28. Scenario: Internationalization in APIs. Accept-Language: en-US; Return localized messages.
  29. How to handle deprecation? Warn in headers: X-Deprecated: true. Migrate clients.
  30. What is hypermedia type? Formats like HAL for links. Example: application/hal+json.
  31. Scenario: API for user roles. Use RBAC; Check permissions per endpoint.
  32. Explain async APIs with queues. Use RabbitMQ; API accepts, queues job. Return job ID.
  33. How to test APIs automatically? Use Jest/Supertest. Example: test('GET /users', () => expect(status).toBe(200)).
  34. Scenario: Handle timeouts. Set server timeouts; Client retries with backoff.
  35. What is OpenAPI specification? Standard for documenting APIs. Example: YAML file with paths, schemas.
  36. Explain idempotency keys. Client-generated key for safe retries. Scenario: Payments.
  37. Scenario: API for graphs/data relationships. Use GraphQL instead, but in REST: Include related data or links.
  38. How to compress responses? Content-Encoding: gzip if client accepts.
  39. What are web API best practices? Use nouns for resources, HTTP methods correctly.
  40. Scenario: Logging in APIs. Log requests/responses without sensitive data.
  41. Explain conditional requests. If-None-Match for caching. Return 304 Not Modified.
  42. How to handle file downloads? GET /files/id with Content-Disposition: attachment.
  43. Scenario: Multi-tenant APIs. Use tenant ID in paths or headers.
  44. What is API orchestration? Coordinate multiple services. Example: Saga pattern.
  45. Explain versioning strategies pros/cons. URL: Simple but URL clutter; Header: Clean but complex.
  46. Scenario: Secure API from injections. Sanitize inputs, use prepared statements.
  47. How to implement search with Elasticsearch? Proxy requests to ES via API endpoint.
  48. What is API federation? Combine subgraph APIs.
  49. Scenario: Handle API evolution. Backward compatibility, feature flags.
  50. Explain request tracing. Use headers like X-Request-ID for distributed tracing.

Expert Level: Competitive, Coding Examples, Analytical, and IQ Challenges

Expert questions are for senior roles, focusing on complex scenarios, code implementations, and deep analysis.

  1. Coding: Implement a REST endpoint in Node.js for user creation with validation.
javascript
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  if (!name || !email) return res.status(400).json({error: 'Missing fields'});
  // Save to DB
  res.status(201).json({id: 1, name, email});
});

Analytical: Use Joi for advanced validation. Real-life: Prevent SQL injections.

  1. Scenario: Optimize a high-traffic API suffering from database bottlenecks. Implement read replicas, caching layers like Memcached. IQ: Calculate QPS; Shard DB if needed. Competitive: In exams, discuss CAP theorem trade-offs.
  2. Explain circuit breakers in API resilience. Pattern to fail fast on downstream failures. Example: Using Hystrix-like libs. Analytical: Prevents cascading failures in microservices.
  3. Coding: Write a Python Flask endpoint with JWT auth.
python
from flask import Flask, request, jsonify
import jwt
app = Flask(__name__)
@app.route('/protected', methods=['GET'])
def protected():
    token = request.headers.get('Authorization').split()[1]
    try:
        data = jwt.decode(token, 'secret', algorithms=['HS256'])
        return jsonify({'message': 'Success', 'user': data['sub']})
    except:
        return jsonify({'error': 'Invalid token'}), 401

Scenario: Secure admin routes.

  1. How to implement API gateway with load balancing? Use NGINX or AWS API Gateway. Analytical: Route based on paths, add SSL termination.
  2. Scenario: Design a distributed system API with eventual consistency. Use CQRS/ES; APIs for commands/queries. IQ: Handle conflicts with version numbers.
  3. Explain gRPC vs. REST for performance. gRPC uses HTTP/2, protobufs for faster binary. Competitive: Better for internal services.
  4. Coding: Implement pagination with cursors in Go.
go
package main
import "net/http"
func handler(w http.ResponseWriter, r *http.Request) {
    cursor := r.URL.Query().Get("cursor")
    limit := 10 // parse from query
    // Fetch from DB with cursor
    // Return next_cursor in response
}

Analytical: Cursors avoid offset slowness in large datasets.

  1. What is service mesh in API ecosystems? Infrastructure layer for service communication, e.g., Istio. Real-life: Traffic management.
  2. Scenario: Handle GDPR compliance in APIs. Add endpoints for data deletion/export. Analytical: Anonymize logs.
  3. Explain zero-trust security for APIs. Verify every request. Example: Mutual TLS.
  4. Coding: Async API response in Java Spring. Use @Async or DeferredResult. Example: Return CompletableFuture.
  5. How to benchmark API performance? Tools like Apache Bench. Measure throughput, latency.
  6. Scenario: Migrate from monolith to microservices APIs. Strangler pattern: Gradually replace endpoints.
  7. What is API contract testing? Pact for consumer-driven contracts.
  8. Coding: Rate limiter in Ruby Sinatra. Use Rack::Attack. Example: throttle('req/ip', limit: 100, period: 3600).
  9. Explain blue-green deployments for APIs. Switch traffic between versions. Analytical: Zero downtime.
  10. Scenario: API for machine learning inference. POST /predict with data; Return probabilities. Handle scaling.
  11. What is backpressure in streaming APIs? Control data flow to prevent overload.
  12. Coding: HATEOAS in ASP.NET. Add links to models. Example: _links: { self: { href: "/api/item/1" } }.
  13. How to implement feature toggles in APIs? Config-based; Route to new/old logic.
  14. Scenario: Secure against API abuse like scraping. CAPTCHA, user-agent checks.
  15. Explain chaos engineering for APIs. Intentionally inject failures to test resilience.
  16. Coding: Webhook validation in PHP. Verify signature with HMAC.
  17. What is API monetization? Usage-based billing. Example: Stripe-like.
  18. Scenario: Handle schema evolution in APIs. Use protobuf for backward compat.
  19. Explain mutual authentication. Client and server certs.
  20. Coding: Batch processing endpoint. Accept array, process in transaction.
  21. How to use OpenTelemetry for tracing? Instrument code for spans.
  22. Scenario: API for blockchain integrations. REST wrapper over nodes.
  23. What is event sourcing in APIs? Store events, replay for state.
  24. Coding: Conditional PUT with ETag in Express. Check req.headers['if-match'].
  25. Explain server-sent events (SSE). For real-time push. Alternative to WS.
  26. Scenario: Design fault-tolerant API. Retries, fallbacks.
  27. What is API federation with Apollo? Combine GraphQL but adaptable to REST.
  28. Coding: Compression middleware in Node. Use compression package.
  29. How to audit API usage? Log all requests, analyze.
  30. Scenario: International API with currencies. Accept header for locale.
  31. Explain canary releases. Rollout to subset of users.
  32. Coding: OAuth client in Python. Use requests-oauthlib.
  33. What is SPIFFE for identity? Workload identities in services.
  34. Scenario: API for IoT devices. Lightweight, MQTT over REST.
  35. Explain adaptive rate limiting. Based on user behavior.
  36. Coding: Schema validation with Yup. In JS: yup.object().shape({name: yup.string().required()}).
  37. How to handle long-running requests? Async with polling endpoint.
  38. Scenario: API governance. Standards enforcement.
  39. What is RSocket? Reactive protocol over REST.
  40. Coding: Deprecation warning header. res.set('Warning', '299 - Deprecated').
  41. Explain API security scanning. Tools like OWASP ZAP.
  42. Scenario: Scale API to millions of users. CDN, auto-scaling, database optimization. IQ: Discuss trade-offs in consistency vs. availability.
  43. Bonus Analytical: Compare REST with GraphQL for complex queries. GraphQL reduces over-fetching; REST needs multiple calls. Real-life: Use GraphQL for flexible clients.
  44. Coding: Implement a simple cache in memory. Use Map in JS for key-response caching.

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here