Web API

Web API

Top Interview Questions

About Web API

 

Web API: An In-Depth Overview

In today’s digital world, seamless communication between applications is a fundamental requirement. Web APIs have emerged as a powerful mechanism that enables this interaction. A Web API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate over the internet. Unlike traditional APIs, which may operate locally, Web APIs operate over the web using standard protocols such as HTTP/HTTPS.

Web APIs are crucial in modern software development because they allow developers to integrate third-party services, access remote data, and build scalable applications efficiently. They act as a bridge between the client and server, enabling requests and responses in a structured format.


Key Concepts of Web API

  1. Request-Response Mechanism
    At its core, a Web API functions on a request-response model. A client application, which could be a web browser, mobile app, or other software, sends an HTTP request to the API endpoint. The server processes the request and sends back an appropriate HTTP response. These responses typically contain data formatted in JSON (JavaScript Object Notation) or XML (eXtensible Markup Language), which are easily interpretable by client applications.

  2. HTTP Methods
    Web APIs utilize standard HTTP methods to define operations:

    • GET: Retrieves data from the server.

    • POST: Sends new data to the server for creation.

    • PUT: Updates existing data on the server.

    • DELETE: Removes data from the server.
      These methods align with CRUD operations (Create, Read, Update, Delete) commonly used in databases and application development.

  3. Endpoints and URLs
    An API endpoint is a specific URL where a client can access resources provided by the API. For example, in an e-commerce system, /products could be an endpoint to fetch all product details, while /products/123 could fetch details of a product with ID 123. Proper structuring of endpoints ensures clarity and usability of the API.

  4. Stateless Communication
    Most modern Web APIs are stateless, meaning each request from the client to the server must contain all the information needed to understand and process it. The server does not store any client session data between requests. This stateless nature improves scalability and simplifies server-side implementation.


Types of Web APIs

Web APIs can be broadly classified into several categories based on their functionality and accessibility:

  1. Open APIs (Public APIs)
    These APIs are publicly available to developers and can be accessed without special permissions. For example, Google Maps API allows developers to integrate maps into their applications.

  2. Partner APIs
    Partner APIs are shared with specific business partners. They are not publicly accessible and usually require an API key or other authentication methods. They help businesses provide controlled access to their services.

  3. Internal APIs (Private APIs)
    Internal APIs are used within an organization. They are not exposed to external users but allow different teams or systems within the company to interact with one another efficiently.

  4. Composite APIs
    Composite APIs allow clients to access multiple endpoints in a single call. This is particularly useful when an application needs data from multiple sources simultaneously, reducing latency and improving performance.


Web API Protocols and Standards

  1. REST (Representational State Transfer)
    REST is the most widely used architectural style for Web APIs. It leverages standard HTTP methods, is stateless, and focuses on resources (data entities) identified by URLs. REST APIs are simple, scalable, and easy to consume by clients.

  2. SOAP (Simple Object Access Protocol)
    SOAP is a protocol that uses XML for message formatting and relies on standards like WSDL (Web Services Description Language) for defining services. SOAP APIs are more rigid and heavyweight than REST, but they provide higher security and reliability, making them suitable for enterprise-level applications such as banking and telecommunications.

  3. GraphQL
    GraphQL, developed by Facebook, is a query language for APIs. Unlike REST, where clients might over-fetch or under-fetch data, GraphQL allows clients to request exactly the data they need. This reduces bandwidth usage and improves performance.

  4. gRPC
    gRPC is a modern RPC (Remote Procedure Call) framework that uses HTTP/2 for transport and Protocol Buffers for data serialization. It is highly efficient, supports bidirectional streaming, and is commonly used in microservices architectures.


Authentication and Security

Web APIs often expose sensitive data or critical operations, so security is paramount. Common authentication and security mechanisms include:

  1. API Keys
    Simple tokens provided to clients to identify them and allow access. API keys are easy to implement but not highly secure on their own.

  2. OAuth (Open Authorization)
    OAuth allows clients to access resources on behalf of a user without exposing their credentials. OAuth 2.0 is widely used by APIs like Google, Facebook, and Twitter.

  3. JWT (JSON Web Tokens)
    JWTs are used to securely transmit information between client and server. They are compact, self-contained, and often used in stateless authentication.

  4. HTTPS
    All secure Web APIs use HTTPS to encrypt data in transit, preventing eavesdropping and man-in-the-middle attacks.


Advantages of Web APIs

  1. Interoperability
    Web APIs allow applications built in different programming languages or platforms to communicate seamlessly. For instance, a Java-based backend can serve a ReactJS frontend using a REST API.

  2. Scalability
    APIs enable applications to scale easily by separating the client and server layers. Developers can improve or modify backend services without affecting client applications.

  3. Reusability
    APIs encapsulate functionality and make it reusable. For example, a payment API can be used by multiple applications across a business ecosystem.

  4. Faster Development
    Developers can leverage third-party APIs to add features without building them from scratch, reducing development time and cost.

  5. Microservices Architecture Support
    APIs are fundamental to microservices, where each service exposes a set of APIs for other services to consume, enabling modular and maintainable applications.


Challenges in Web API Development

Despite their advantages, Web APIs come with challenges:

  1. Versioning
    As APIs evolve, maintaining backward compatibility is crucial. Versioning strategies like /v1/products vs. /v2/products are common.

  2. Rate Limiting
    APIs exposed to external clients often implement rate limiting to prevent abuse and ensure fair usage.

  3. Data Consistency
    In distributed systems, ensuring data consistency across APIs can be challenging.

  4. Security Threats
    APIs can be targeted by attacks such as injection, cross-site scripting (XSS), and denial of service (DoS). Robust security measures are necessary.


Real-World Examples of Web APIs

  1. Social Media APIs
    Facebook Graph API, Twitter API, and Instagram API allow developers to access social media data, post updates, and interact with users programmatically.

  2. Payment APIs
    Stripe, PayPal, and Razorpay APIs enable secure online payment integration for e-commerce websites and mobile applications.

  3. Mapping and Location APIs
    Google Maps API, Mapbox, and OpenStreetMap APIs provide geolocation services, route planning, and map integration.

  4. Weather APIs
    OpenWeatherMap and Weatherstack APIs provide real-time weather data and forecasts for various regions.

Fresher Interview Questions

 

1. What is a Web API?

Answer:
A Web API (Application Programming Interface) is a set of rules that allows applications to communicate with each other over the internet. It enables developers to access features or data of an application from another application.

  • Example: Using the Twitter API to fetch tweets in your app.

  • Key Points:

    • APIs expose functionality without revealing the internal code.

    • They typically use HTTP methods (GET, POST, PUT, DELETE).

    • They return data in formats like JSON or XML.


2. What are the different types of Web APIs?

Answer:
Web APIs can be categorized as:

  1. REST (Representational State Transfer):

    • Most common type.

    • Stateless and uses standard HTTP methods.

    • Example: GET /users/1

  2. SOAP (Simple Object Access Protocol):

    • Older protocol using XML.

    • Supports built-in error handling and security.

    • Example: Banking or enterprise systems often use SOAP.

  3. GraphQL:

    • A query language for APIs.

    • Client requests exactly the data it needs.

    • Example: Fetching user profile and posts in a single query.

  4. JSON-RPC / XML-RPC:

    • Remote Procedure Call protocols using JSON or XML.


3. What is RESTful API?

Answer:
A RESTful API is an API that follows REST principles:

  • Stateless: Each request contains all the information needed.

  • Client-Server Architecture: Separation of client and server responsibilities.

  • Cacheable: Responses can be cached for performance.

  • Uniform Interface: Consistent URI and HTTP method usage.

HTTP Methods in REST:

  • GET: Retrieve data

  • POST: Create new data

  • PUT: Update existing data

  • DELETE: Delete data


4. Difference between REST and SOAP

Feature REST SOAP
Protocol HTTP XML-based protocol
Format JSON, XML, HTML, Text XML only
Complexity Simple Complex
Performance Faster Slower
Statefulness Stateless Can be Stateful
Security HTTPS, OAuth WS-Security

5. What is JSON and XML?

Answer:

  • JSON (JavaScript Object Notation):

    • Lightweight data format.

    • Easy to read/write.

    • Commonly used in REST APIs.

    • Example:

      {
        "name": "Yash",
        "age": 25
      }
      
  • XML (Extensible Markup Language):

    • Markup language to store structured data.

    • More verbose than JSON.

    • Common in SOAP APIs.

    • Example:

      <user>
        <name>Yash</name>
        <age>25</age>
      </user>
      

6. What are HTTP methods and their use?

Answer:

  • GET: Retrieve data from the server.

  • POST: Send data to create a new resource.

  • PUT: Update an existing resource.

  • PATCH: Partially update a resource.

  • DELETE: Remove a resource.

Example:

GET /users/1       # Fetch user with ID 1
POST /users        # Create a new user
PUT /users/1       # Update user with ID 1
DELETE /users/1    # Delete user with ID 1

7. What is an endpoint in Web API?

Answer:
An endpoint is a URL where an API can be accessed by a client application.

  • Example: https://api.example.com/users/123

  • Here, /users/123 is the endpoint to get user details with ID 123.


8. What is an API key?

Answer:
An API key is a unique identifier used to authenticate requests to an API.

  • Prevents unauthorized access.

  • Often passed in request headers or URL parameters.

Example:

GET /users?apikey=12345abcdef

9. What is the difference between API and Web Service?

Feature API Web Service
Communication Can use any protocol Uses network protocols (HTTP, SOAP)
Format JSON, XML, HTML XML (mostly)
Accessibility Local or over the internet Over the internet only
Types REST, SOAP, GraphQL SOAP, REST

10. What is status code in Web API?

Answer:
Status codes indicate the result of an HTTP request.

Common Status Codes:

  • 200 OK: Success

  • 201 Created: Resource created

  • 400 Bad Request: Client error

  • 401 Unauthorized: Invalid credentials

  • 403 Forbidden: Access denied

  • 404 Not Found: Resource not found

  • 500 Internal Server Error: Server-side error


11. What is Authentication and Authorization in APIs?

Answer:

  • Authentication: Verifying who the user is.

    • Example: Login credentials, OAuth tokens.

  • Authorization: Determining what resources a user can access.

    • Example: Admin vs regular user permissions.


12. What is REST API versioning?

Answer:
Versioning ensures backward compatibility when API updates occur.

  • Methods:

    1. URI versioning: /v1/users

    2. Header versioning: Accept: application/vnd.example.v1+json


13. What is CORS?

Answer:
CORS (Cross-Origin Resource Sharing) allows a web application from one domain to access resources on another domain.

  • Prevents unauthorized cross-domain requests.

  • Configured on the server using headers like:

    Access-Control-Allow-Origin: *
    

14. What is API throttling and rate limiting?

Answer:

  • Throttling: Limiting the number of requests in a given time.

  • Rate Limiting: Restricting API usage to prevent abuse.

  • Example: Twitter API allows 900 requests per 15 minutes.


15. How do you test Web APIs?

Answer:
APIs can be tested using tools:

  • Postman: Send requests and view responses.

  • Swagger: API documentation and testing.

  • Curl: Command-line testing.

Example:

curl -X GET https://api.example.com/users/1

16. What is Swagger?

Answer:
Swagger is a tool for designing, building, documenting, and testing REST APIs.

  • Provides interactive API documentation.

  • Helps developers understand endpoints, request/response format, and status codes.


17. Difference between PUT and PATCH

Feature PUT PATCH
Update Updates entire resource Updates partial resource
Idempotent Yes Usually yes
Request Body Full object Only fields to update

18. What is idempotent API?

Answer:
An API is idempotent if performing the same operation multiple times produces the same result.

  • GET, PUT, DELETE are idempotent.

  • POST is not idempotent because it creates a new resource every time.


19. What is HATEOAS?

Answer:
HATEOAS (Hypermedia As The Engine Of Application State) is a REST constraint that allows clients to dynamically navigate API resources using hyperlinks.

  • Example: Response for /users/1 might include links for /users/1/orders or /users/1/friends.


20. Difference between REST and GraphQL

Feature REST GraphQL
Data Fetch Multiple endpoints required Single endpoint
Overfetching Possible Not possible
Flexibility Fixed response structure Client-defined structure
Query URL and parameters Query language

21. What is API Documentation? Why is it important?

Answer:
API documentation is a technical guide that explains how to use an API. It includes endpoints, methods, request/response format, headers, authentication, and examples.

Importance:

  • Helps developers understand how to use the API.

  • Reduces errors during integration.

  • Provides a reference for testing and debugging.

  • Tools like Swagger/OpenAPI are used for auto-generated documentation.


22. What is JWT (JSON Web Token)?

Answer:
JWT is a token-based authentication mechanism often used in REST APIs. It allows secure transmission of information between client and server.

  • Structure: Header.Payload.Signature

  • Example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOjEsIm5hbWUiOiJYYXNoIn0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
  • Use Cases: Authentication, single sign-on, stateless sessions.


23. What are query parameters and path parameters?

Answer:

  • Query Parameters: Key-value pairs sent after ? in URL, mainly for filtering or sorting.

    • Example: /users?age=25&status=active

  • Path Parameters: Part of the URL path to identify a specific resource.

    • Example: /users/123123 is the path parameter.


24. What is API versioning and why is it needed?

Answer:
API versioning ensures that updates to the API do not break existing client applications.

  • Methods:

    1. URI Versioning: /api/v1/users

    2. Header Versioning: Accept: application/vnd.example.v1+json

    3. Query Parameter Versioning: /api/users?version=1

  • Ensures backward compatibility for existing clients.


25. What is an HTTP header? Give examples.

Answer:
HTTP headers pass metadata about the request or response. They include content type, authentication, caching, etc.

Common Headers:

  • Content-Type: application/json → Specifies request/response format.

  • Authorization: Bearer <token> → Used for authentication.

  • Accept: application/xml → Client’s preferred response format.

  • Cache-Control: no-cache → Controls caching behavior.


26. How do you secure a Web API?

Answer:
API security is crucial to protect sensitive data. Methods include:

  1. Authentication: OAuth2, JWT, API keys

  2. Authorization: Role-based access control (RBAC)

  3. HTTPS: Encrypt data during transit

  4. Rate limiting & throttling: Prevent abuse

  5. Input validation & sanitization: Prevent SQL injection or XSS

  6. CORS policies: Restrict cross-origin access


27. What is API caching?

Answer:
API caching stores responses temporarily to reduce server load and improve performance.

  • Types of caching:

    • Client-side caching: Stored in browser or app.

    • Server-side caching: Stored in the server or proxy.

  • Example Headers:

    Cache-Control: max-age=3600
    

28. Difference between synchronous and asynchronous APIs

Feature Synchronous API Asynchronous API
Request Flow Client waits for response Client continues without waiting
Response Time Immediate Can be delayed
Example REST API GET request Webhooks, Event-driven APIs
Use Case Simple CRUD operations Notifications, messaging, background tasks

29. What is API rate limiting?

Answer:
Rate limiting restricts the number of API requests a client can make within a time window.

  • Prevents server overload and abuse.

  • Example: 1000 requests per hour.

  • Response Header Example:

X-Rate-Limit-Limit: 1000
X-Rate-Limit-Remaining: 750

30. What is HATEOAS in REST API?

Answer:
HATEOAS (Hypermedia as the Engine of Application State) allows clients to discover available actions dynamically via hyperlinks in API responses.

Example:

{
  "id": 1,
  "name": "Yash",
  "links": [
    {"rel": "self", "href": "/users/1"},
    {"rel": "orders", "href": "/users/1/orders"}
  ]
}

31. How do you handle errors in Web API?

Answer:
API error handling uses HTTP status codes and a structured response message.

Example Response:

{
  "status": 404,
  "error": "Not Found",
  "message": "User with ID 123 not found"
}
  • Best Practices:

    • Use standard HTTP status codes

    • Include meaningful error messages

    • Log errors for debugging


32. What are Webhooks?

Answer:
A webhook is a way for an API to push data to a client in real-time when an event occurs.

  • Unlike APIs, which are request-driven, webhooks are event-driven.

  • Example: GitHub sending a payload to your app when a new commit is pushed.


33. Difference between SOAP and REST

Feature SOAP REST
Protocol Strict protocol (XML) Architectural style
Format XML only JSON, XML, Text, HTML
Performance Slower due to verbosity Faster, lightweight
Security WS-Security HTTPS, OAuth
Use Case Enterprise systems, banking Web apps, mobile apps

34. What is API mocking?

Answer:
API mocking is creating a fake API that simulates real API behavior for testing.

  • Helps frontend developers continue work before backend is ready.

  • Tools: Postman, Swagger, Mockoon, WireMock


35. How do you test a REST API using Postman?

Answer:

  1. Open Postman and create a new request.

  2. Select the HTTP method (GET, POST, PUT, DELETE).

  3. Enter the endpoint URL.

  4. Add headers if required (Content-Type, Authorization).

  5. Add request body for POST/PUT requests.

  6. Click Send to get the response.

  7. Validate response body, status code, and headers.


36. Difference between PUT and POST

Feature POST PUT
Purpose Create new resource Update existing resource
Idempotency Not idempotent Idempotent
Request Body Contains data to create Contains full data to update
URI API decides resource ID Client specifies resource ID

37. What is OAuth 2.0?

Answer:
OAuth 2.0 is an authorization framework that allows apps to access resources on behalf of a user without exposing credentials.

  • Roles:

    1. Resource Owner (User)

    2. Client (App requesting access)

    3. Authorization Server (Issues tokens)

    4. Resource Server (API server)

  • Example Flow: Login with Google in a third-party app.


38. Difference between API Gateway and API

Feature API API Gateway
Function Exposes endpoints for communication Manages, routes, secures APIs
Responsibilities CRUD operations Security, rate limiting, caching, logging
Example REST API /users AWS API Gateway

39. What is SOAP Fault?

Answer:
A SOAP Fault is an error message in a SOAP response. It includes:

  • faultcode → Type of error

  • faultstring → Error description

  • detail → Additional info

Example:

<fault>
  <faultcode>Client</faultcode>
  <faultstring>Invalid ID</faultstring>
</fault>

40. Difference between PUT, PATCH, and POST

Method Use Case Idempotent Partial Update
POST Create new resource No No
PUT Update/Replace existing resource Yes No
PATCH Partially update resource Yes Yes

41. What is REST API idempotency?

Answer:
An API is idempotent if performing the same request multiple times results in the same state on the server.

  • GET, PUT, DELETE → Idempotent

  • POST → Not idempotent (creates new resource each time)

Example:

PUT /users/1
Body: {"name":"Yash"}
  • Updating a user with PUT multiple times has the same effect as once.


42. What is API throttling vs rate limiting?

Answer:

Feature Throttling Rate Limiting
Purpose Slow down excessive requests Limit requests per time frame
Example Delay every 5th request Max 1000 requests/hour
Goal Protect server stability Prevent abuse

43. What is the difference between REST API and WebSocket?

Feature REST API WebSocket
Communication Request-response Full-duplex, real-time
Use Case CRUD operations Chat apps, live updates
Protocol HTTP WS or WSS
Statefulness Stateless Stateful connection

44. What is the difference between HTTP and HTTPS?

Answer:

Feature HTTP HTTPS
Security Not encrypted Encrypted with SSL/TLS
Port 80 443
Use Case Public info, testing Sensitive data, login

45. How do you handle authentication in APIs?

Answer:
Common authentication methods:

  1. API Keys: Simple, static keys.

  2. Basic Auth: Username/password in request header (not recommended without HTTPS).

  3. OAuth2: Token-based, secure, widely used.

  4. JWT: Stateless, signed tokens for authentication.

Example (Bearer Token in header):

Authorization: Bearer <token>

46. What is API versioning and why is it important?

Answer:
Versioning allows APIs to evolve without breaking existing clients.

  • Methods:

    1. URI Versioning: /api/v1/users

    2. Header Versioning: Accept: application/vnd.example.v1+json

    3. Query Parameter: /users?version=1

Importance:

  • Maintains backward compatibility.

  • Allows gradual deprecation of old versions.


47. What is API gateway and its advantages?

Answer:
An API Gateway is an intermediary between clients and backend services.

  • Advantages:

    • Centralized authentication & authorization

    • Request routing & load balancing

    • Rate limiting & throttling

    • Response caching & monitoring

Example: AWS API Gateway, Kong


48. What is REST API statelessness?

Answer:
REST APIs are stateless, meaning each request contains all information needed for processing.

  • Server does not store client state between requests.

  • Advantages: Easier scaling, less memory usage.

Example:

GET /users/1
Authorization: Bearer <token>
  • Server processes request only based on current input.


49. What is API mocking?

Answer:
API mocking creates a fake API for testing purposes.

  • Benefits:

    • Frontend can work before backend is ready.

    • Simulates real API responses.

Tools: Postman, Swagger, WireMock


50. What are webhooks?

Answer:
Webhooks are event-driven notifications sent from server to client.

  • Unlike regular APIs (client requests data), webhooks push data automatically.

  • Example: GitHub sending a POST request when a new commit occurs.


51. What is the difference between PUT, POST, and PATCH?

Method Use Case Idempotent Partial Update
POST Create new resource No No
PUT Update/replace entire resource Yes No
PATCH Partially update resource Yes Yes

52. What is HATEOAS in REST API?

Answer:
HATEOAS allows clients to dynamically navigate REST APIs using hyperlinks in the response.

Example:

{
  "id": 1,
  "name": "Yash",
  "links": [
    {"rel": "self", "href": "/users/1"},
    {"rel": "orders", "href": "/users/1/orders"}
  ]
}

53. What is CORS and how do you handle it?

Answer:
CORS (Cross-Origin Resource Sharing) allows restricted resources on a web page to be requested from another domain.

  • Handled via HTTP headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT
  • Prevents unauthorized cross-origin requests.


54. What is API caching?

Answer:
API caching stores responses to reduce server load and improve response times.

  • Client-side caching: Browser caches API response.

  • Server-side caching: Server stores response in memory or Redis.

  • Headers:

Cache-Control: max-age=3600

55. How do you handle errors in Web API?

Answer:

  • Use HTTP status codes and structured response body.

Example Response:

{
  "status": 404,
  "error": "Not Found",
  "message": "User with ID 123 not found"
}

Best Practices:

  • Meaningful messages

  • Logging for debugging

  • Avoid exposing sensitive info


56. Difference between synchronous and asynchronous APIs

Feature Synchronous API Asynchronous API
Request Flow Client waits for response Client continues without waiting
Response Time Immediate Can be delayed
Example REST API GET request Webhooks, Event-driven APIs
Use Case Simple CRUD operations Notifications, messaging, background tasks

57. Difference between REST API and GraphQL

Feature REST GraphQL
Endpoint Multiple endpoints Single endpoint
Data Fetch Fixed response structure Client requests exactly needed data
Overfetching Possible Not possible
Flexibility Less flexible High flexibility
Versioning Needed Not needed

58. How do you secure Web APIs?

Answer:

  1. Authentication: OAuth2, JWT, API keys

  2. Authorization: Role-based access control

  3. HTTPS: Encrypt data in transit

  4. Rate limiting: Prevent abuse

  5. Input validation: Avoid SQL injection / XSS

  6. CORS restrictions: Control cross-origin access


59. What are API testing tools?

Answer:
Common tools:

  • Postman: Manual testing, automation

  • Swagger: Documentation + testing

  • SoapUI: SOAP/REST testing

  • Curl: Command-line testing

Example:

curl -X GET https://api.example.com/users/1

60. What is OAuth 2.0?

Answer:
OAuth 2.0 is an authorization framework allowing apps to access resources on behalf of a user without sharing credentials.

  • Roles:

    • Resource Owner: User

    • Client: App requesting access

    • Authorization Server: Issues tokens

    • Resource Server: API server

  • Example: Login with Google/Facebook.


61. What is JWT and how does it work?

Answer:
JWT (JSON Web Token) is a stateless authentication token.

  • Structure: Header.Payload.Signature

  • Use Case: Authenticate API requests without session storage.

  • Flow:

    1. User logs in → Server issues JWT

    2. Client sends JWT in Authorization header

    3. Server validates JWT → Grants access


62. What is SOAP Fault?

Answer:
SOAP Fault is an error response in SOAP API.

  • Contains faultcode, faultstring, and optional detail.

Example:

<fault>
  <faultcode>Client</faultcode>
  <faultstring>Invalid ID</faultstring>
</fault>

Experienced Interview Questions

 

1. What is REST API and why is it preferred?

Answer:
REST (Representational State Transfer) is an architectural style for building scalable web services.

Key Features:

  • Stateless: Each request contains all information.

  • Cacheable: Responses can be cached for performance.

  • Uniform Interface: Consistent use of HTTP methods.

  • Client-Server Separation: Easy to maintain and scale.

Why preferred:

  • Lightweight (JSON over XML)

  • Easy to integrate with web/mobile apps

  • Supports CRUD operations efficiently


2. Explain the difference between REST and SOAP.

Feature REST SOAP
Protocol HTTP XML-based protocol
Format JSON, XML, HTML XML only
Statefulness Stateless Can be Stateful
Performance Fast, lightweight Slower, verbose
Security HTTPS, OAuth WS-Security
Use Case Mobile/Web apps Enterprise, banking, legacy systems

3. What is HATEOAS and how is it implemented?

Answer:
HATEOAS (Hypermedia As The Engine of Application State) allows REST clients to navigate APIs dynamically using hyperlinks.

Example Response:

{
  "id": 1,
  "name": "Yash",
  "links": [
    {"rel": "self", "href": "/users/1"},
    {"rel": "orders", "href": "/users/1/orders"}
  ]
}
  • Reduces client hardcoding URLs.

  • Improves discoverability of API resources.


4. What are the best practices for designing REST APIs?

Answer:

  1. Use plural nouns for resources: /users instead of /user.

  2. Use HTTP methods consistently (GET, POST, PUT, DELETE).

  3. Return appropriate status codes (200, 201, 400, 404, 500).

  4. Implement versioning: /api/v1/users.

  5. Support filtering, sorting, and pagination for large datasets.

  6. Use HATEOAS for discoverability.

  7. Secure API with HTTPS, OAuth2, JWT.

  8. Proper error handling with descriptive messages.


5. How do you secure REST APIs in production?

Answer:

  • Authentication: OAuth2, JWT, API keys

  • Authorization: Role-based access control (RBAC)

  • HTTPS: Encrypt data in transit

  • Rate Limiting & Throttling: Prevent abuse

  • Input Validation & Sanitization: Prevent SQL injection/XSS

  • CORS policies: Restrict cross-origin access

  • Logging & Monitoring: Track suspicious activities


6. What is JWT and how does it differ from OAuth2?

Answer:

  • JWT (JSON Web Token): A compact token used for stateless authentication.

    • Contains user info in payload and is signed.

    • Example header: Authorization: Bearer <token>

  • OAuth2: Authorization framework to allow third-party apps access without sharing credentials.

    • OAuth2 can use JWT as access tokens.

    • JWT is token format; OAuth2 is protocol/flow.


7. Explain API versioning strategies.

Answer:
API versioning ensures backward compatibility.

  • URI Versioning: /api/v1/users

  • Header Versioning: Accept: application/vnd.example.v1+json

  • Query Parameter Versioning: /users?version=1

  • Semantic Versioning: v1.0, v1.1, v2.0

Best Practice: URI versioning is widely used for clarity.


8. How do you handle API rate limiting?

Answer:
Rate limiting restricts the number of requests a client can make within a given time.

  • Techniques:

    1. Fixed Window: Max requests per time window

    2. Sliding Window: Smooths bursts of requests

    3. Token Bucket: Tokens consumed per request

  • Implementation:

    • API Gateway (AWS API Gateway, Kong)

    • Redis-based counters for distributed systems


9. How do you handle large payloads in REST APIs?

Answer:

  1. Pagination: Return data in pages (limit and offset).

  2. Filtering: Return only required fields.

  3. Compression: Use gzip or Brotli.

  4. Streaming: Stream large responses instead of loading entire data in memory.

  5. Batch processing: Divide large requests into smaller batches.


10. What is CORS and how do you implement it?

Answer:
CORS (Cross-Origin Resource Sharing) allows web applications from one origin to access resources from another.

  • Controlled via HTTP headers:

Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
  • For APIs, configure server to allow only trusted origins.


11. How do you handle error responses in production APIs?

Answer:

  • Use HTTP status codes to indicate result.

    • 2xx → Success

    • 4xx → Client errors

    • 5xx → Server errors

  • Return structured JSON:

{
  "status": 404,
  "error": "Not Found",
  "message": "User with ID 123 not found"
}
  • Log errors for debugging.

  • Avoid exposing sensitive data.


12. What is API caching and how is it implemented?

Answer:
API caching reduces server load and improves performance.

  • Types:

    1. Client-side caching: Browser stores API responses.

    2. Server-side caching: Redis, Memcached.

    3. Proxy caching: Nginx, CDN (CloudFront).

  • HTTP Headers:

Cache-Control: max-age=3600
ETag: "abc123"
  • Use caching carefully for dynamic or sensitive data.


13. What is API throttling and why is it needed?

Answer:

  • Throttling limits requests to prevent server overload.

  • Example: Delay every nth request or limit per second.

  • Helps maintain availability during high traffic.


14. How do you implement API logging and monitoring?

Answer:

  • Logging: Track request, response, user info, errors.

    • Tools: ELK Stack, Graylog, Splunk

  • Monitoring: Track performance metrics, latency, error rates.

    • Tools: Prometheus, Grafana, New Relic

  • Logs and monitoring help debug, optimize, and secure APIs.


15. How do you test APIs in production?

Answer:

  1. Functional testing: Validate endpoints return correct data.

  2. Load testing: Ensure API can handle expected traffic.

    • Tools: JMeter, Locust

  3. Security testing: Test authentication, authorization, injection attacks.

  4. Automation testing: Postman/Newman, Selenium for API flows.

  5. Mocking: Test APIs without hitting production resources.


16. Difference between PUT, PATCH, and POST in production APIs

Method Use Case Idempotent Partial Update
POST Create resource No No
PUT Replace existing resource Yes No
PATCH Update partial resource Yes Yes

Best Practice: Use PATCH for partial updates to avoid sending full payload.


17. How do you secure APIs against attacks?

Answer:

  • Authentication: OAuth2, JWT

  • Authorization: RBAC, scopes

  • Input Validation: SQL injection, XSS prevention

  • HTTPS: Encrypt data in transit

  • Rate Limiting & Throttling: Prevent abuse

  • CORS Restrictions: Control cross-origin requests

  • Logging & Monitoring: Detect suspicious activity


18. Explain OAuth2 flow in detail.

Answer:
OAuth2 allows third-party apps to access user data securely without sharing credentials.

  • Roles:

    1. Resource Owner → User

    2. Client → App requesting access

    3. Authorization Server → Issues token

    4. Resource Server → Hosts API

Flow:

  1. Client requests authorization.

  2. User authenticates.

  3. Authorization server issues access token.

  4. Client calls API with token.

  5. Server validates token and responds.

Types of grants: Authorization code, Implicit, Client credentials, Resource owner password credentials


19. What is API Gateway and why is it used?

Answer:
An API Gateway sits between clients and backend services.

Responsibilities:

  • Request routing

  • Load balancing

  • Authentication & authorization

  • Rate limiting & throttling

  • Caching & response transformation

  • Logging & monitoring

Example: AWS API Gateway, Kong, Apigee


20. How do you optimize API performance?

Answer:

  1. Caching: Client, server, proxy

  2. Pagination & filtering: For large datasets

  3. Compression: Gzip/Brotli for payloads

  4. Asynchronous processing: Background tasks

  5. Database optimization: Indexing, optimized queries

  6. Connection pooling: For database/API connections

  7. Load balancing: Scale horizontally


21. What is API throttling and why is it important?

Answer:
API throttling is controlling the number of requests a client can send in a given period to prevent overloading the server.

  • Importance:

    • Prevents server crashes due to spikes in traffic

    • Protects APIs from abuse or DDoS attacks

    • Maintains fair usage among clients

Implementation Examples:

  • Fixed window: 100 requests per minute

  • Token bucket algorithm for smooth bursts


22. Explain API caching strategies for production APIs.

Answer:
Caching improves response time and reduces server load.

  • Client-side caching: Browser caches response (Cache-Control, ETag)

  • Server-side caching: Redis, Memcached

  • Proxy/CDN caching: Nginx, CloudFront

  • Best Practices:

    • Cache GET requests only

    • Avoid caching sensitive/private data

    • Use cache invalidation on updates


23. How do you design APIs for high traffic?

Answer:

  • Load balancing: Distribute requests across multiple servers

  • Rate limiting & throttling: Prevent abuse

  • Caching: Reduce repeated database calls

  • Asynchronous processing: Use queues for long-running tasks

  • Pagination & filtering: Avoid sending large datasets in a single request

  • Connection pooling: Reuse database/API connections


24. How do you handle API versioning in microservices?

Answer:

  • URI versioning: /v1/users

  • Header versioning: Accept: application/vnd.example.v1+json

  • Backward compatibility: Avoid breaking existing clients

  • Microservices strategy:

    • Each microservice manages its version independently

    • Use API Gateway to route clients to appropriate versions


25. Difference between synchronous and asynchronous API calls.

Feature Synchronous API Asynchronous API
Request Flow Client waits for response Client continues execution
Use Case CRUD operations Notifications, events
Latency Immediate response required Response can be delayed
Examples REST API GET request Webhooks, message queues

26. What are Webhooks and how are they different from APIs?

Answer:

  • Webhooks: Event-driven mechanism where server pushes data to a client automatically.

  • APIs: Client requests data explicitly.

Example:

  • GitHub Webhook → POST request to your server when a new commit occurs.

  • Difference: Webhooks are push-based, APIs are pull-based.


27. Explain OAuth2 and JWT together.

Answer:

  • OAuth2: Framework for authorization, often used to grant third-party apps access.

  • JWT: Token format often used in OAuth2 as access token.

Flow Example:

  1. Client requests authorization → OAuth2 server

  2. Server issues JWT as access token

  3. Client sends JWT in Authorization header

  4. API server validates JWT → Grants access

  • JWT allows stateless authentication and reduces server-side session storage.


28. How do you secure APIs against common attacks?

Answer:

  1. Authentication & Authorization: OAuth2, JWT, API keys, RBAC

  2. HTTPS: Encrypt all requests/responses

  3. Input validation: Prevent SQL injection and XSS

  4. Rate limiting: Prevent DDoS

  5. CORS policies: Limit cross-origin access

  6. Logging & monitoring: Detect suspicious activities


29. Explain API Gateway in microservices.

Answer:

  • API Gateway is a single entry point for all client requests to microservices.

Responsibilities:

  • Request routing to appropriate microservice

  • Authentication & Authorization

  • Rate limiting & throttling

  • Caching and response transformation

  • Logging & monitoring

Examples: AWS API Gateway, Kong, Apigee


30. How do you optimize API performance?

Answer:

  1. Caching: Client, server, or CDN caching

  2. Compression: Use Gzip/Brotli

  3. Pagination & filtering: Limit large datasets

  4. Database optimization: Indexing, optimized queries

  5. Asynchronous processing: Queues for heavy tasks

  6. Connection pooling: Efficient DB/API connections

  7. Load balancing: Horizontal scaling

  8. CDN usage: Offload static content


31. How do you handle large payloads?

Answer:

  • Pagination: Return data in chunks

  • Filtering: Return only required fields

  • Streaming: Stream responses instead of loading entire payload in memory

  • Compression: Gzip/Brotli

  • Batch processing: Divide requests into smaller parts


32. How do you handle API errors in production?

Answer:

  • Use HTTP status codes: 2xx (success), 4xx (client errors), 5xx (server errors)

  • Structured JSON response:

{
  "status": 404,
  "error": "Not Found",
  "message": "User with ID 123 not found"
}
  • Logging: Log errors for debugging

  • Avoid exposing sensitive information


33. How do you implement API rate limiting in distributed systems?

Answer:

  • Centralized store: Redis to track request counts

  • Sliding window algorithm: Smooth bursts

  • Token bucket algorithm: Allow fixed requests and replenish tokens

  • API Gateway: Implement rate limiting at gateway level


34. Explain difference between PUT, PATCH, and POST.

Method Use Case Idempotent Partial Update
POST Create resource No No
PUT Replace entire resource Yes No
PATCH Partial update Yes Yes

Best Practice: Use PATCH for partial updates to reduce payload size.


35. What is HATEOAS and how does it improve REST APIs?

Answer:

  • HATEOAS allows clients to navigate APIs dynamically using hyperlinks in responses.

Example:

{
  "id": 1,
  "name": "Yash",
  "links": [
    {"rel": "self", "href": "/users/1"},
    {"rel": "orders", "href": "/users/1/orders"}
  ]
}
  • Reduces hardcoding of URLs in client apps

  • Improves API discoverability


36. How do you implement authentication for microservices?

Answer:

  1. Centralized authentication service: OAuth2 or JWT

  2. Token passing: Each request includes JWT token

  3. API Gateway validation: Token validation at gateway before routing

  4. RBAC: Assign roles/permissions for each service


37. How do you handle backward compatibility in APIs?

Answer:

  • Avoid breaking existing endpoints

  • Add new endpoints or versions for new features

  • Use optional fields in response JSON

  • Maintain proper API documentation

  • Deprecate old versions gradually


38. How do you implement logging and monitoring for APIs?

Answer:

  • Logging: Track request/response, status codes, errors

  • Tools: ELK Stack, Splunk, Graylog

  • Monitoring: Metrics like latency, throughput, error rate

  • Tools: Prometheus, Grafana, New Relic

  • Helps in debugging, performance tuning, and security


39. Explain synchronous vs asynchronous API in microservices.

Answer:

  • Synchronous API: Client waits for response (REST GET/POST)

  • Asynchronous API: Client continues; response delivered via queue or webhook

  • Use Case:

    • Sync: CRUD operations

    • Async: Notifications, email sending, batch jobs


40. What is API mocking and why is it used?

Answer:

  • API mocking simulates API responses without hitting real backend services.

  • Uses:

    • Frontend development before backend is ready

    • Testing error scenarios

    • Performance testing

Tools: Postman, WireMock, Swagger


41. What are the common strategies to handle API versioning in production?

Answer:
Versioning ensures backward compatibility and smooth API evolution. Common strategies include:

  1. URI Versioning:

    /api/v1/users
    
    • Most common, clear and easy to maintain.

  2. Header Versioning:

    Accept: application/vnd.example.v1+json
    
    • Clean URL, suitable for content negotiation.

  3. Query Parameter Versioning:

    /users?version=1
    
    • Easy to implement, but can clutter URLs.

  4. Semantic Versioning:

    • Use major/minor version numbers: v1.0, v1.1, v2.0

    • Helps indicate backward-incompatible changes.


42. How do you implement rate limiting for distributed APIs?

Answer:
Rate limiting prevents abuse and ensures fair usage. For distributed systems:

  • Centralized store approach: Use Redis to track request counts per client.

  • Sliding window algorithm: Smoothens request spikes.

  • Token bucket algorithm: Allows bursts of requests but limits overall usage.

  • API Gateway implementation: AWS API Gateway, Kong, or Nginx.

Example:

X-Rate-Limit-Limit: 1000
X-Rate-Limit-Remaining: 750

43. How do you optimize API performance for high traffic?

Answer:

  1. Caching: Client, server, CDN (Redis, CloudFront)

  2. Pagination & filtering: Limit large datasets in a single request

  3. Compression: Gzip or Brotli for payload

  4. Connection pooling: Efficient DB/API connections

  5. Asynchronous processing: Queues for long-running tasks

  6. Load balancing: Distribute traffic horizontally

  7. Database optimization: Indexing, query optimization

  8. CDN usage: Offload static content


44. What is the difference between synchronous and asynchronous APIs in microservices?

Feature Synchronous API Asynchronous API
Request Flow Client waits for response Client continues execution
Use Case CRUD operations Notifications, email, batch jobs
Protocols HTTP/HTTPS Message queues (Kafka, RabbitMQ)
Latency Immediate response required Response can be delayed

45. How do you implement authentication across microservices?

Answer:

  1. Centralized Authentication Service: OAuth2 server or JWT issuing service

  2. Token Passing: Each request includes JWT token in Authorization header

  3. API Gateway Validation: Validate token before routing requests to microservices

  4. Role-based Access Control (RBAC): Each service verifies permissions


46. What is API Gateway and why is it used?

Answer:
An API Gateway is a single entry point for clients to interact with multiple microservices.

Responsibilities:

  • Request routing to proper microservice

  • Authentication & authorization

  • Rate limiting & throttling

  • Caching responses

  • Logging & monitoring

  • Load balancing

Examples: AWS API Gateway, Kong, Apigee


47. How do you handle large payloads in APIs?

Answer:

  • Pagination: Return data in chunks (limit and offset)

  • Filtering & Field Selection: Return only required fields

  • Streaming: Stream large responses instead of loading into memory

  • Compression: Use Gzip/Brotli

  • Batch Processing: Divide large operations into smaller requests


48. How do you handle errors and exceptions in production APIs?

Answer:

  • Use standard HTTP status codes:

    • 2xx → Success

    • 4xx → Client errors

    • 5xx → Server errors

  • Provide structured JSON responses:

{
  "status": 404,
  "error": "Not Found",
  "message": "User with ID 123 not found"
}
  • Logging: Log errors for debugging and monitoring

  • Do not expose sensitive info


49. What are Webhooks and how are they used in real-time scenarios?

Answer:

  • Webhooks are event-driven API callbacks where the server pushes data to a client endpoint.

  • Used for real-time updates without polling.

  • Example:

    • GitHub webhook → Notify your app when a new commit is pushed

    • Payment gateways → Notify when a payment is completed


50. Explain OAuth2 flow with JWT for API authentication.

Answer:

  1. Client requests authorization → OAuth2 server

  2. User authenticates → Authorization granted

  3. Server issues JWT access token

  4. Client sends JWT in Authorization header with each request

  5. Server validates JWT → Grants access

  • JWT ensures stateless authentication

  • Scalable for microservices without server session storage


51. How do you secure APIs against common attacks?

Answer:

  1. Authentication & Authorization: OAuth2, JWT, API keys, RBAC

  2. HTTPS: Encrypt all requests/responses

  3. Input Validation: Prevent SQL injection, XSS

  4. Rate Limiting & Throttling: Protect against DDoS

  5. CORS Policies: Control cross-origin access

  6. Logging & Monitoring: Detect suspicious activity


52. How do you implement logging and monitoring for APIs?

Answer:

  • Logging: Request/response payloads, headers, errors, latency

  • Tools: ELK Stack, Splunk, Graylog

  • Monitoring: Track metrics like response time, error rate, throughput

  • Tools: Prometheus, Grafana, New Relic

  • Helps with debugging, optimization, and security analysis


53. How do you ensure backward compatibility in APIs?

Answer:

  • Avoid breaking existing endpoints

  • Use optional fields instead of removing existing fields

  • Maintain old versions alongside new versions

  • Document changes clearly in API documentation

  • Deprecate old versions gradually


54. Explain HATEOAS in REST APIs.

Answer:

  • HATEOAS allows clients to navigate REST APIs dynamically using hyperlinks.

Example Response:

{
  "id": 1,
  "name": "Yash",
  "links": [
    {"rel": "self", "href": "/users/1"},
    {"rel": "orders", "href": "/users/1/orders"}
  ]
}
  • Improves API discoverability

  • Reduces client-side hardcoding of URLs


55. Difference between PUT, PATCH, and POST in production APIs

Method Use Case Idempotent Partial Update
POST Create resource No No
PUT Replace entire resource Yes No
PATCH Partial update Yes Yes

Best Practice: Use PATCH for partial updates to reduce payload size and network traffic.


56. How do you design APIs for microservices architecture?

Answer:

  • Loose coupling: Each microservice has its own API and database

  • Use API Gateway: Single entry point with routing, authentication, and throttling

  • Asynchronous communication: Use message queues (Kafka, RabbitMQ) for inter-service communication

  • Idempotency: Ensure repeated requests don’t cause inconsistent states

  • Versioning: Each microservice manages its own versions


57. How do you handle concurrency in APIs?

Answer:

  • Use optimistic locking: Version number or timestamp checks

  • Use pessimistic locking: Lock resource for a single transaction

  • Use atomic operations in DB

  • Ensure idempotency to avoid duplicate processing


58. How do you monitor API performance and health in production?

Answer:

  • Track latency, error rates, throughput, CPU/memory usage

  • Use APM tools: New Relic, Datadog, Prometheus + Grafana

  • Set alerts for thresholds

  • Implement circuit breaker pattern for dependent services


59. How do you implement distributed caching for APIs?

Answer:

  • Use Redis or Memcached as a centralized cache

  • Cache GET responses only

  • Use cache keys based on resource + query parameters

  • Implement cache invalidation strategies: TTL, manual eviction, or event-based


60. How do you handle API payload validation?

Answer:

  • Validate required fields and data types

  • Use JSON schema validation

  • Sanitize inputs to prevent SQL injection, XSS

  • Return meaningful error messages

  • Validate file uploads and sizes if applicable