Top Interview Questions
A Web API (Application Programming Interface) is a set of protocols, routines, and tools that allow software applications to communicate with each other over the internet. It acts as a bridge between different software systems, enabling them to exchange data and functionality without needing to understand each other’s internal code.
Web APIs are essential in modern software development, powering everything from mobile apps and web applications to cloud services and IoT devices. They enable interoperability, automation, and scalability, making them a backbone of the digital ecosystem.
A Web API is essentially a web-based interface that allows developers to access or manipulate data and services provided by a server. The term “Web” indicates that the API uses standard web protocols like HTTP/HTTPS for communication.
Key characteristics of a Web API:
HTTP Methods: Uses methods like GET, POST, PUT, DELETE to interact with resources.
Data Formats: Supports standard formats such as JSON (JavaScript Object Notation), XML (Extensible Markup Language), or HTML.
Stateless Communication: Most modern APIs follow the REST architecture, meaning each request is independent.
Web APIs enable developers to integrate external services into their applications, such as payment gateways, social media platforms, cloud storage, and geolocation services.
APIs have been around for decades as software components for communication between programs. However, the rise of the internet gave birth to Web APIs, allowing interaction over the web. Key milestones include:
SOAP (Simple Object Access Protocol): Early web APIs using XML and HTTP for structured communication.
REST (Representational State Transfer): Introduced in 2000 by Roy Fielding, emphasizing stateless operations, scalability, and simplicity.
JSON-based APIs: Lightweight, human-readable, and faster than XML, becoming the standard for modern web development.
GraphQL: Developed by Facebook for efficient, flexible queries.
Today, Web APIs are central to cloud computing, microservices, and mobile-first development.
The architecture of a Web API defines how clients and servers interact. Most Web APIs follow the client-server model, where:
Client: Sends requests to the server. Can be a browser, mobile app, IoT device, or another server.
Server: Processes requests and returns responses, often with data in JSON or XML format.
Web APIs commonly follow two architectural styles:
Stateless: Each request contains all necessary information.
Resource-Based: Everything is treated as a resource identified by a URL.
HTTP Methods: GET for reading data, POST for creating, PUT for updating, DELETE for removing.
Lightweight: Uses JSON/XML for data exchange.
Protocol-Based: Uses XML to structure messages.
Strict Standards: Enforces security, transactions, and formal contracts using WSDL (Web Services Description Language).
Heavyweight: Better for enterprise applications requiring guaranteed security and compliance.
Modern APIs are mostly RESTful due to simplicity and performance, while SOAP is used in legacy enterprise systems.
Platform Independence: Can be used across different programming languages and platforms.
Standardized Communication: Uses HTTP and standard formats for seamless interaction.
Scalability: Supports multiple clients simultaneously with minimal overhead.
Security: Supports authentication methods like OAuth 2.0, API keys, and JWT (JSON Web Tokens).
Extensibility: Can be extended to include new endpoints or services without affecting existing clients.
Interoperability: Enables integration between different applications, services, and devices.
Web APIs can be classified based on access and functionality:
Accessible to external developers.
Often used to integrate third-party services.
Examples: Google Maps API, Twitter API, Stripe API.
Used within an organization to connect internal systems.
Improves modularity and maintainability of large applications.
Shared with business partners to provide controlled access.
Example: Payment gateways exposing APIs to merchants.
Combine multiple endpoints into a single API call.
Useful in microservices architectures to reduce multiple network requests.
Web APIs power modern digital applications across various industries:
Social Media Integration: APIs enable sharing, posting, and retrieving social media content within apps.
Payment Processing: Stripe, PayPal, and other payment APIs handle transactions securely.
Cloud Services: APIs connect apps with cloud storage, computing, or SaaS platforms.
IoT Devices: APIs allow devices to communicate and exchange data over the internet.
Data Analytics: APIs provide access to large datasets, financial markets, and real-time analytics.
E-commerce: APIs manage product catalogs, inventory, shipping, and customer information.
Efficiency: Allows developers to reuse existing services instead of building from scratch.
Automation: Enables automated workflows and integration between different systems.
Innovation: Provides building blocks for creating new applications and services.
Flexibility: Supports multiple clients like web apps, mobile apps, and desktop apps.
Faster Time-to-Market: Reduces development time by leveraging third-party APIs.
Enhanced User Experience: Real-time data exchange allows apps to provide dynamic content.
Use RESTful Principles: Keep APIs stateless and resource-based.
Version Your API: Maintain backward compatibility and enable smooth upgrades.
Secure Your API: Use HTTPS, OAuth, and token-based authentication.
Consistent Naming Conventions: Use clear, descriptive endpoints.
Rate Limiting: Prevent abuse by limiting the number of requests per client.
Detailed Documentation: Ensure developers understand endpoints, request formats, and responses.
Error Handling: Provide clear error messages and HTTP status codes.
While the terms are often used interchangeably, there are differences:
| Feature | Web API | Web Service |
|---|---|---|
| Protocol | Any (HTTP, WebSocket, TCP) | SOAP (usually over HTTP) |
| Data Format | JSON, XML, HTML | XML |
| Platform | Platform-independent | Platform-independent |
| Flexibility | High (supports REST, GraphQL, etc.) | Limited (follows SOAP standards) |
Web APIs are evolving with technology trends:
GraphQL and API Query Languages: Provide efficient, flexible data retrieval.
API-First Development: Designing APIs as the core component of software.
Serverless APIs: Cloud providers like AWS and Azure allow APIs without managing servers.
Microservices Integration: APIs are essential for connecting microservices architectures.
AI-Driven APIs: APIs provide access to AI and machine learning services for natural language processing, computer vision, and predictive analytics.
A Web API is the backbone of modern software development, enabling applications, devices, and services to communicate seamlessly over the web. By providing standardized interfaces, Web APIs allow developers to integrate third-party services, automate workflows, and build scalable, data-driven applications.
With the rise of cloud computing, microservices, IoT, and mobile applications, Web APIs have become indispensable for innovation, efficiency, and interoperability. Whether you are building a web application, mobile app, or enterprise system, understanding and leveraging Web APIs is essential for modern software development.
Q1. What is a Web API?
Answer:
"A Web API (Application Programming Interface) allows different software applications to communicate over the web using HTTP protocols. It exposes endpoints that clients can consume to perform operations like GET, POST, PUT, DELETE."
Q2. Difference between API and Web API
| Feature | API | Web API |
|---|---|---|
| Communication | Can be local or remote | Remote over HTTP/HTTPS |
| Protocol | Any (function calls, RPC, etc.) | HTTP/HTTPS |
| Example | OS API, library API | REST API, SOAP API |
Q3. What is REST?
Answer:
"REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful APIs use HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations and are stateless, cacheable, and scalable."
Q4. What is SOAP?
Answer:
"SOAP (Simple Object Access Protocol) is a protocol for exchanging structured XML messages over HTTP, SMTP, or other protocols. It emphasizes strict standards, security, and formal contracts via WSDL."
Q5. Difference between REST and SOAP
| Feature | REST | SOAP |
|---|---|---|
| Protocol | HTTP only | HTTP, SMTP, TCP |
| Message Format | JSON, XML | XML |
| Performance | Lightweight | Heavy |
| Security | OAuth, HTTPS | WS-Security |
| Stateless | Yes | Can be stateful |
Q6. What are HTTP methods commonly used in Web APIs?
GET: Retrieve data
POST: Create new data
PUT: Update existing data completely
PATCH: Update existing data partially
DELETE: Remove data
Q7. What are HTTP status codes?
"Status codes indicate the result of an HTTP request. Common ones include:
200 OK: Success
201 Created: Resource created
400 Bad Request: Client error
401 Unauthorized: Authentication failed
403 Forbidden: Access denied
404 Not Found: Resource not found
500 Internal Server Error: Server-side error"*
Q8. Difference between PUT and PATCH
| Feature | PUT | PATCH |
|---|---|---|
| Purpose | Complete update | Partial update |
| Idempotent | Yes | Usually yes, but can vary |
Q9. What are headers in HTTP requests?
"Headers carry metadata such as content type (Content-Type), authorization (Authorization), caching (Cache-Control), and custom information to communicate additional info between client and server."
Q10. What is the difference between query parameters and path parameters?
Query parameters: Used to filter or sort resources (/users?age=25)
Path parameters: Used to specify resource ID (/users/123)
Q11. What are the principles of REST?
Stateless – No client context stored on server
Client-Server – Separation of concerns
Cacheable – Responses should define caching
Uniform Interface – Standard methods for CRUD
Layered System – Architecture can have intermediaries
Code on Demand (optional) – Server can send executable code
Q12. What is an endpoint in Web API?
"An endpoint is a URL exposed by the server that clients can call to perform operations on resources."
Example: /users, /products/123
Q13. What is the difference between resource and representation?
Resource: Entity like user, product
Representation: Format of resource data returned, e.g., JSON, XML
Q14. How do you version a REST API?
"Versioning ensures backward compatibility. Common approaches:
URI versioning: /v1/users
Header versioning: Accept: application/vnd.example.v1+json
Query parameter: /users?version=1"
Q15. What is HATEOAS?
"Hypermedia as the Engine of Application State – clients navigate API dynamically using links provided in responses instead of hardcoding URIs."
Q16. What is authentication in Web API?
"Authentication verifies the identity of a client using credentials like API key, OAuth token, JWT, or username/password."
Q17. What is authorization?
"Authorization determines what resources or operations an authenticated client can access."
Q18. Difference between authentication and authorization
| Feature | Authentication | Authorization |
|---|---|---|
| Purpose | Verify identity | Check permissions |
| When | Before accessing system | After authentication |
| Example | Login | Admin rights |
Q19. What is JWT (JSON Web Token)?
"JWT is a compact, URL-safe token format used to transmit claims between client and server for authentication and authorization. It consists of header, payload, and signature."
Q20. How do you secure a Web API?
Use HTTPS
Implement authentication & authorization (JWT, OAuth2)
Validate input to prevent injection attacks
Rate limiting and throttling
Use API gateway for centralized control
Q21. What is JSON and why is it preferred?
"JSON (JavaScript Object Notation) is lightweight, human-readable, and language-independent. Widely used in REST APIs because of simplicity and smaller payload size."
Q22. Difference between JSON and XML
| Feature | JSON | XML |
|---|---|---|
| Size | Lightweight | Larger |
| Readability | Easy | Verbose |
| Parsing | Simple in JavaScript | Needs XML parser |
| Data Types | Supports native types | All values are strings |
Q23. How do you send data in POST request?
Send data in body as JSON, XML, or form-data
Set Content-Type header to application/json or application/x-www-form-urlencoded
Q24. What is query string vs request body?
Query string: Data sent in URL for GET requests
Request body: Data sent in POST/PUT/PATCH requests
Q25. What tools are used to test Web APIs?
Postman
Swagger / OpenAPI
SoapUI
curl command-line tool
Automated tests with JUnit, pytest, or REST-assured
Q26. What is Swagger / OpenAPI?
"Swagger (OpenAPI) is a framework for designing, documenting, and testing REST APIs. It provides interactive documentation and contract definitions."
Q27. Difference between unit testing and API testing
| Feature | Unit Testing | API Testing |
|---|---|---|
| Scope | Individual function/method | API endpoint integration |
| Purpose | Validate internal logic | Validate request/response |
| Tools | JUnit, NUnit, pytest | Postman, REST-assured |
Q28. What is mocking in API testing?
"Mocking simulates API responses when the actual API or backend is not available, allowing testing of dependent services."
Q29. Difference between synchronous and asynchronous API calls
Synchronous: Client waits for server response before continuing
Asynchronous: Client continues execution and handles response later
Q30. What is rate limiting?
"Rate limiting restricts the number of API calls a client can make in a time window to prevent abuse and ensure fair usage."
Q31. What is statelessness in REST?
"Each API request should contain all information needed to process it. The server does not store client state between requests."
Q32. What are API gateways?
"API gateway acts as a single entry point for clients to access multiple microservices. It handles routing, authentication, rate limiting, and logging."
Q33. What is throttling?
"Throttling limits API usage for a client to prevent overloading the server."
Q34. Difference between monolithic API and microservices API
| Feature | Monolithic | Microservices |
|---|---|---|
| Deployment | Single app | Multiple services |
| Scalability | Hard | Easy |
| Fault Isolation | Low | High |
Q35. What are idempotent operations in Web API?
"Idempotent operations produce the same result no matter how many times the request is repeated. Examples: GET, PUT, DELETE."
Q36. What is content negotiation?
"Content negotiation allows the client to specify the preferred format (JSON, XML) using Accept header and server responds accordingly."
Q37. What is caching in Web API?
"Caching stores the response of API requests temporarily to improve performance and reduce server load. Controlled via headers like Cache-Control and ETag."
Q38. Difference between synchronous and asynchronous APIs
Synchronous: Client waits for response (blocking)
Asynchronous: Client continues execution, response handled via callback, webhook, or polling
Q39. What is a webhook?
"Webhook is a user-defined HTTP callback triggered by specific events on the server. Server pushes data to client endpoint instead of client polling."
Q40. What is API versioning and why is it important?
"Versioning allows you to introduce changes without breaking existing clients. Methods include URI versioning, header versioning, and query parameters."
Q41. How do you handle errors in Web APIs?
Use meaningful HTTP status codes
Provide error messages in response body
Implement logging for debugging
Handle validation and exceptions gracefully
Q42. Difference between PUT and POST in REST
| Feature | POST | PUT |
|---|---|---|
| Use | Create resource | Update resource |
| Idempotent | No | Yes |
| Request body | Contains data to create | Contains full updated data |
Q43. Difference between REST API and GraphQL
| Feature | REST API | GraphQL |
|---|---|---|
| Data fetching | Multiple endpoints | Single endpoint, query-based |
| Over-fetching | Possible | Avoided |
| Flexibility | Fixed response structure | Client defines structure |
Q44. What is OAuth 2.0?
"OAuth 2.0 is an authorization framework that allows third-party apps to access user data securely without sharing credentials using access tokens."
Q45. Difference between API key and OAuth
| Feature | API Key | OAuth |
|---|---|---|
| Security | Simple, less secure | More secure, token-based |
| Use case | Server-to-server | User authorization |
| Expiry | Usually permanent | Short-lived tokens |
Answer:
A Web API (Application Programming Interface) is a set of protocols and tools that allow different software applications to communicate over the web. Web APIs enable developers to expose functionality (like data retrieval, CRUD operations, or business logic) via HTTP endpoints.
Answer:
| Type | Definition |
|---|---|
| API | General interface for software interaction (local or remote) |
| Web API | API accessible over HTTP/HTTPS |
| REST API | Web API that follows REST principles (stateless, resource-based, uses HTTP verbs) |
Answer:
| Feature | SOAP | REST |
|---|---|---|
| Protocol | Strict, XML-based | Architectural style, flexible formats (JSON, XML) |
| State | Stateful or stateless | Stateless |
| Security | WS-Security | HTTPS, OAuth |
| Performance | Slower | Faster, lightweight |
Answer:
GET: Retrieve resource
POST: Create resource
PUT: Update resource (replace)
PATCH: Update resource (partial)
DELETE: Delete resource
Answer:
Idempotent operations produce the same result regardless of how many times they are performed.
Example: GET /users/123 or PUT /users/123
Answer:
Each request contains all information required for the server to process it.
Server does not store client state between requests.
Advantages: scalability, easier caching, failure tolerance
Answer:
Hypermedia as the Engine of Application State
REST responses include links to related actions for client navigation
Example: Returning GET /orders/123 with links to update or delete
Answer:
Synchronous: Client waits for server response; blocking call
Asynchronous: Client continues execution; server notifies when processing completes
Answer:
Managing changes in API while keeping backward compatibility
Techniques:
URL versioning: /api/v1/users
Header versioning: Accept: application/vnd.myapi.v1+json
Query param: /users?version=1
Answer:
Path parameter: Part of URL; identifies resource (/users/123)
Query parameter: Optional parameters; filtering, sorting (/users?role=admin)
Answer:
200 OK: Successful GET/PUT/PATCH
201 Created: Successful POST
204 No Content: Successful DELETE
400 Bad Request: Client error
401 Unauthorized: Missing/invalid authentication
403 Forbidden: Access denied
404 Not Found: Resource does not exist
500 Internal Server Error: Server-side error
Answer:
Authentication: Verifies identity (username/password, JWT, OAuth token)
Authorization: Determines access permissions (roles, scopes)
Answer:
Token-based stateless authentication mechanism
Contains header, payload, and signature
Server validates signature; payload contains user claims (id, roles)
Example: Authorization: Bearer <token>
Answer:
OAuth 2.0 is simpler, token-based, widely used
OAuth 1.0 uses signatures and encryption for each request
OAuth 2.0 supports access token, refresh token, scopes
Answer:
Browser security feature that blocks requests from different origins
Server sends Access-Control-Allow-Origin header to allow requests
Answer:
HTTP: Unencrypted, insecure
HTTPS: SSL/TLS encryption, secure data transfer, authentication of server
Answer:
Prevents abuse by limiting number of requests per client per time window
Example: 1000 requests per hour
Answer:
PUT: Replaces entire resource
PATCH: Modifies only specified fields
Answer:
Storing responses to reduce server load
Implemented via HTTP headers:
Cache-Control, ETag, Last-Modified
Answer:
GET, PUT, DELETE are idempotent
POST is not idempotent
Answer:
Use plural nouns for resources: /users
Use HTTP verbs correctly
Implement pagination, filtering, sorting
Consistent error responses
Versioning for backward compatibility
Use JSON format for payloads
Answer:
Hypermedia links in responses
Improves discoverability and self-documenting APIs
Answer:
Use Swagger/OpenAPI
Include request/response examples
Document authentication and error codes
Answer:
RESTful: Follows REST constraints (stateless, resource-oriented, standard verbs)
RESTless: Violates REST principles (RPC-style, actions in URL)
Answer:
Simulate API responses before backend is ready
Tools: Postman, WireMock, Swagger Mock
Answer:
Query params: /users?page=2&limit=20
Use offset and limit
Response can include total count, next/prev links
Answer:
Synchronous: /login returns token immediately
Asynchronous: /report triggers processing, client polls /report/status
Answer:
URI-based: /v1/users
Header-based: Accept: application/vnd.myapi.v1+json
Query parameter: /users?version=1
Allows backward compatibility
Answer:
Single entry point for all API calls
Handles authentication, rate limiting, logging, request routing
Answer:
| Feature | REST | GraphQL |
|---|---|---|
| Data fetching | Fixed endpoints | Flexible queries |
| Overfetching | Possible | No overfetching |
| Versioning | Needed | Not needed |
| Complexity | Simple | Higher learning curve |
Answer:
Standard HTTP status codes
Error payload includes: code, message, details
Example JSON:
{ "code": 400, "message": "Invalid input", "details": "Email is required" }
Answer:
Client-side (4xx): Bad request, unauthorized, forbidden, not found
Server-side (5xx): Internal server error, database failures
Answer:
Middleware or filters (e.g., ASP.NET Core ExceptionFilter, Java Spring @ControllerAdvice)
Returns consistent JSON error response
Answer:
Optimistic: Assume no conflict; check version/timestamp before update
Pessimistic: Lock resource to prevent concurrent edits
Answer:
Fail-fast: Detect errors immediately, stop processing
Graceful degradation: Return partial results or cached data while service partially fails
Answer:
Enable caching (HTTP headers, Redis)
Use pagination and filtering
Compress payloads (gzip)
Avoid overfetching
Optimize database queries
Answer:
Prevent abuse and server overload
Limit requests per client (e.g., 1000 per hour)
Answer:
Distribute requests across multiple instances
Ensures high availability and scalability
Tools: Nginx, AWS ELB
Answer:
Use streaming instead of loading in memory
Chunked uploads
Limit file size in server configuration
Answer:
HTTPS for encryption
Authentication: OAuth, JWT
Authorization: Roles, scopes
Rate limiting / throttling
Input validation to prevent injections
Answer:
Follow RESTful conventions
Include versioning
Standardized error handling
Implement caching, logging, monitoring
Ensure scalability and security