Top Interview Questions
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.
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.
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.
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.
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.
Web APIs can be broadly classified into several categories based on their functionality and accessibility:
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.
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.
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.
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.
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.
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.
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.
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.
Web APIs often expose sensitive data or critical operations, so security is paramount. Common authentication and security mechanisms include:
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.
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.
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.
HTTPS
All secure Web APIs use HTTPS to encrypt data in transit, preventing eavesdropping and man-in-the-middle attacks.
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.
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.
Reusability
APIs encapsulate functionality and make it reusable. For example, a payment API can be used by multiple applications across a business ecosystem.
Faster Development
Developers can leverage third-party APIs to add features without building them from scratch, reducing development time and cost.
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.
Despite their advantages, Web APIs come with challenges:
Versioning
As APIs evolve, maintaining backward compatibility is crucial. Versioning strategies like /v1/products vs. /v2/products are common.
Rate Limiting
APIs exposed to external clients often implement rate limiting to prevent abuse and ensure fair usage.
Data Consistency
In distributed systems, ensuring data consistency across APIs can be challenging.
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.
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.
Payment APIs
Stripe, PayPal, and Razorpay APIs enable secure online payment integration for e-commerce websites and mobile applications.
Mapping and Location APIs
Google Maps API, Mapbox, and OpenStreetMap APIs provide geolocation services, route planning, and map integration.
Weather APIs
OpenWeatherMap and Weatherstack APIs provide real-time weather data and forecasts for various regions.
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.
Answer:
Web APIs can be categorized as:
REST (Representational State Transfer):
Most common type.
Stateless and uses standard HTTP methods.
Example: GET /users/1
SOAP (Simple Object Access Protocol):
Older protocol using XML.
Supports built-in error handling and security.
Example: Banking or enterprise systems often use SOAP.
GraphQL:
A query language for APIs.
Client requests exactly the data it needs.
Example: Fetching user profile and posts in a single query.
JSON-RPC / XML-RPC:
Remote Procedure Call protocols using JSON or XML.
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
| 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 |
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>
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
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.
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
| 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 |
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
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.
Answer:
Versioning ensures backward compatibility when API updates occur.
Methods:
URI versioning: /v1/users
Header versioning: Accept: application/vnd.example.v1+json
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: *
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.
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
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.
| Feature | PUT | PATCH |
|---|---|---|
| Update | Updates entire resource | Updates partial resource |
| Idempotent | Yes | Usually yes |
| Request Body | Full object | Only fields to update |
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.
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.
| 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 |
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.
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.
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/123 → 123 is the path parameter.
Answer:
API versioning ensures that updates to the API do not break existing client applications.
Methods:
URI Versioning: /api/v1/users
Header Versioning: Accept: application/vnd.example.v1+json
Query Parameter Versioning: /api/users?version=1
Ensures backward compatibility for existing clients.
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.
Answer:
API security is crucial to protect sensitive data. Methods include:
Authentication: OAuth2, JWT, API keys
Authorization: Role-based access control (RBAC)
HTTPS: Encrypt data during transit
Rate limiting & throttling: Prevent abuse
Input validation & sanitization: Prevent SQL injection or XSS
CORS policies: Restrict cross-origin access
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
| 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 |
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
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"}
]
}
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
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.
| 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 |
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
Answer:
Open Postman and create a new request.
Select the HTTP method (GET, POST, PUT, DELETE).
Enter the endpoint URL.
Add headers if required (Content-Type, Authorization).
Add request body for POST/PUT requests.
Click Send to get the response.
Validate response body, status code, and headers.
| 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 |
Answer:
OAuth 2.0 is an authorization framework that allows apps to access resources on behalf of a user without exposing credentials.
Roles:
Resource Owner (User)
Client (App requesting access)
Authorization Server (Issues tokens)
Resource Server (API server)
Example Flow: Login with Google in a third-party app.
| 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 |
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>
| 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 |
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.
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 |
| 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 |
Answer:
| Feature | HTTP | HTTPS |
|---|---|---|
| Security | Not encrypted | Encrypted with SSL/TLS |
| Port | 80 | 443 |
| Use Case | Public info, testing | Sensitive data, login |
Answer:
Common authentication methods:
API Keys: Simple, static keys.
Basic Auth: Username/password in request header (not recommended without HTTPS).
OAuth2: Token-based, secure, widely used.
JWT: Stateless, signed tokens for authentication.
Example (Bearer Token in header):
Authorization: Bearer <token>
Answer:
Versioning allows APIs to evolve without breaking existing clients.
Methods:
URI Versioning: /api/v1/users
Header Versioning: Accept: application/vnd.example.v1+json
Query Parameter: /users?version=1
Importance:
Maintains backward compatibility.
Allows gradual deprecation of old versions.
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
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.
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
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.
| 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 |
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"}
]
}
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.
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
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
| 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 |
| 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 |
Answer:
Authentication: OAuth2, JWT, API keys
Authorization: Role-based access control
HTTPS: Encrypt data in transit
Rate limiting: Prevent abuse
Input validation: Avoid SQL injection / XSS
CORS restrictions: Control cross-origin access
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
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.
Answer:
JWT (JSON Web Token) is a stateless authentication token.
Structure: Header.Payload.Signature
Use Case: Authenticate API requests without session storage.
Flow:
User logs in → Server issues JWT
Client sends JWT in Authorization header
Server validates JWT → Grants access
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>
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
| 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 |
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.
Answer:
Use plural nouns for resources: /users instead of /user.
Use HTTP methods consistently (GET, POST, PUT, DELETE).
Return appropriate status codes (200, 201, 400, 404, 500).
Implement versioning: /api/v1/users.
Support filtering, sorting, and pagination for large datasets.
Use HATEOAS for discoverability.
Secure API with HTTPS, OAuth2, JWT.
Proper error handling with descriptive messages.
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
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.
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.
Answer:
Rate limiting restricts the number of requests a client can make within a given time.
Techniques:
Fixed Window: Max requests per time window
Sliding Window: Smooths bursts of requests
Token Bucket: Tokens consumed per request
Implementation:
API Gateway (AWS API Gateway, Kong)
Redis-based counters for distributed systems
Answer:
Pagination: Return data in pages (limit and offset).
Filtering: Return only required fields.
Compression: Use gzip or Brotli.
Streaming: Stream large responses instead of loading entire data in memory.
Batch processing: Divide large requests into smaller batches.
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.
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.
Answer:
API caching reduces server load and improves performance.
Types:
Client-side caching: Browser stores API responses.
Server-side caching: Redis, Memcached.
Proxy caching: Nginx, CDN (CloudFront).
HTTP Headers:
Cache-Control: max-age=3600
ETag: "abc123"
Use caching carefully for dynamic or sensitive data.
Answer:
Throttling limits requests to prevent server overload.
Example: Delay every nth request or limit per second.
Helps maintain availability during high traffic.
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.
Answer:
Functional testing: Validate endpoints return correct data.
Load testing: Ensure API can handle expected traffic.
Tools: JMeter, Locust
Security testing: Test authentication, authorization, injection attacks.
Automation testing: Postman/Newman, Selenium for API flows.
Mocking: Test APIs without hitting production resources.
| 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.
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
Answer:
OAuth2 allows third-party apps to access user data securely without sharing credentials.
Roles:
Resource Owner → User
Client → App requesting access
Authorization Server → Issues token
Resource Server → Hosts API
Flow:
Client requests authorization.
User authenticates.
Authorization server issues access token.
Client calls API with token.
Server validates token and responds.
Types of grants: Authorization code, Implicit, Client credentials, Resource owner password credentials
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
Answer:
Caching: Client, server, proxy
Pagination & filtering: For large datasets
Compression: Gzip/Brotli for payloads
Asynchronous processing: Background tasks
Database optimization: Indexing, optimized queries
Connection pooling: For database/API connections
Load balancing: Scale horizontally
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
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
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
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
| 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 |
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.
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:
Client requests authorization → OAuth2 server
Server issues JWT as access token
Client sends JWT in Authorization header
API server validates JWT → Grants access
JWT allows stateless authentication and reduces server-side session storage.
Answer:
Authentication & Authorization: OAuth2, JWT, API keys, RBAC
HTTPS: Encrypt all requests/responses
Input validation: Prevent SQL injection and XSS
Rate limiting: Prevent DDoS
CORS policies: Limit cross-origin access
Logging & monitoring: Detect suspicious activities
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
Answer:
Caching: Client, server, or CDN caching
Compression: Use Gzip/Brotli
Pagination & filtering: Limit large datasets
Database optimization: Indexing, optimized queries
Asynchronous processing: Queues for heavy tasks
Connection pooling: Efficient DB/API connections
Load balancing: Horizontal scaling
CDN usage: Offload static content
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
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
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
| 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.
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
Answer:
Centralized authentication service: OAuth2 or JWT
Token passing: Each request includes JWT token
API Gateway validation: Token validation at gateway before routing
RBAC: Assign roles/permissions for each service
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
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
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
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
Answer:
Versioning ensures backward compatibility and smooth API evolution. Common strategies include:
URI Versioning:
/api/v1/users
Most common, clear and easy to maintain.
Header Versioning:
Accept: application/vnd.example.v1+json
Clean URL, suitable for content negotiation.
Query Parameter Versioning:
/users?version=1
Easy to implement, but can clutter URLs.
Semantic Versioning:
Use major/minor version numbers: v1.0, v1.1, v2.0
Helps indicate backward-incompatible changes.
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
Answer:
Caching: Client, server, CDN (Redis, CloudFront)
Pagination & filtering: Limit large datasets in a single request
Compression: Gzip or Brotli for payload
Connection pooling: Efficient DB/API connections
Asynchronous processing: Queues for long-running tasks
Load balancing: Distribute traffic horizontally
Database optimization: Indexing, query optimization
CDN usage: Offload static content
| 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 |
Answer:
Centralized Authentication Service: OAuth2 server or JWT issuing service
Token Passing: Each request includes JWT token in Authorization header
API Gateway Validation: Validate token before routing requests to microservices
Role-based Access Control (RBAC): Each service verifies permissions
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
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
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
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
Answer:
Client requests authorization → OAuth2 server
User authenticates → Authorization granted
Server issues JWT access token
Client sends JWT in Authorization header with each request
Server validates JWT → Grants access
JWT ensures stateless authentication
Scalable for microservices without server session storage
Answer:
Authentication & Authorization: OAuth2, JWT, API keys, RBAC
HTTPS: Encrypt all requests/responses
Input Validation: Prevent SQL injection, XSS
Rate Limiting & Throttling: Protect against DDoS
CORS Policies: Control cross-origin access
Logging & Monitoring: Detect suspicious activity
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
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
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
| 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.
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
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
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
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
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