Web API

Web API

Top Interview Questions

About Web API

 

Understanding Web API

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.


Definition of Web API

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.


History and Evolution

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:

  1. SOAP (Simple Object Access Protocol): Early web APIs using XML and HTTP for structured communication.

  2. REST (Representational State Transfer): Introduced in 2000 by Roy Fielding, emphasizing stateless operations, scalability, and simplicity.

  3. JSON-based APIs: Lightweight, human-readable, and faster than XML, becoming the standard for modern web development.

  4. GraphQL: Developed by Facebook for efficient, flexible queries.

Today, Web APIs are central to cloud computing, microservices, and mobile-first development.


Architecture of a Web API

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:

1. RESTful Architecture

  • 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.

2. SOAP Architecture

  • 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.


Key Features of Web API

  1. Platform Independence: Can be used across different programming languages and platforms.

  2. Standardized Communication: Uses HTTP and standard formats for seamless interaction.

  3. Scalability: Supports multiple clients simultaneously with minimal overhead.

  4. Security: Supports authentication methods like OAuth 2.0, API keys, and JWT (JSON Web Tokens).

  5. Extensibility: Can be extended to include new endpoints or services without affecting existing clients.

  6. Interoperability: Enables integration between different applications, services, and devices.


Types of Web APIs

Web APIs can be classified based on access and functionality:

1. Open/Public APIs

  • Accessible to external developers.

  • Often used to integrate third-party services.

  • Examples: Google Maps API, Twitter API, Stripe API.

2. Private/Internal APIs

  • Used within an organization to connect internal systems.

  • Improves modularity and maintainability of large applications.

3. Partner APIs

  • Shared with business partners to provide controlled access.

  • Example: Payment gateways exposing APIs to merchants.

4. Composite APIs

  • Combine multiple endpoints into a single API call.

  • Useful in microservices architectures to reduce multiple network requests.


Use Cases of Web APIs

Web APIs power modern digital applications across various industries:

  1. Social Media Integration: APIs enable sharing, posting, and retrieving social media content within apps.

  2. Payment Processing: Stripe, PayPal, and other payment APIs handle transactions securely.

  3. Cloud Services: APIs connect apps with cloud storage, computing, or SaaS platforms.

  4. IoT Devices: APIs allow devices to communicate and exchange data over the internet.

  5. Data Analytics: APIs provide access to large datasets, financial markets, and real-time analytics.

  6. E-commerce: APIs manage product catalogs, inventory, shipping, and customer information.


Benefits of Web APIs

  1. Efficiency: Allows developers to reuse existing services instead of building from scratch.

  2. Automation: Enables automated workflows and integration between different systems.

  3. Innovation: Provides building blocks for creating new applications and services.

  4. Flexibility: Supports multiple clients like web apps, mobile apps, and desktop apps.

  5. Faster Time-to-Market: Reduces development time by leveraging third-party APIs.

  6. Enhanced User Experience: Real-time data exchange allows apps to provide dynamic content.


Best Practices in Web API Development

  1. Use RESTful Principles: Keep APIs stateless and resource-based.

  2. Version Your API: Maintain backward compatibility and enable smooth upgrades.

  3. Secure Your API: Use HTTPS, OAuth, and token-based authentication.

  4. Consistent Naming Conventions: Use clear, descriptive endpoints.

  5. Rate Limiting: Prevent abuse by limiting the number of requests per client.

  6. Detailed Documentation: Ensure developers understand endpoints, request formats, and responses.

  7. Error Handling: Provide clear error messages and HTTP status codes.


Web API vs Web Service

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)

Future of Web APIs

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.


Conclusion

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.

Fresher Interview Questions

 

1. Basics of Web API

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

2. HTTP Basics

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)


3. RESTful API Design

Q11. What are the principles of REST?

  1. Stateless – No client context stored on server

  2. Client-Server – Separation of concerns

  3. Cacheable – Responses should define caching

  4. Uniform Interface – Standard methods for CRUD

  5. Layered System – Architecture can have intermediaries

  6. 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."


4. Authentication & Security

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


5. Web API Data Formats

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


6. Web API Testing

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."


7. Web API Architecture & Design

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

Experienced Interview Questions

 

Basic Concepts

1. What is a Web API?

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.


2. Difference between API, Web API, and REST API

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)

3. Difference between SOAP and REST APIs

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

4. Explain HTTP verbs used in REST APIs

Answer:

  • GET: Retrieve resource

  • POST: Create resource

  • PUT: Update resource (replace)

  • PATCH: Update resource (partial)

  • DELETE: Delete resource


5. What is idempotency in Web APIs?

Answer:

  • Idempotent operations produce the same result regardless of how many times they are performed.

  • Example: GET /users/123 or PUT /users/123


6. What is statelessness in REST APIs?

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


7. What is HATEOAS in REST?

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


8. Difference between synchronous and asynchronous APIs

Answer:

  • Synchronous: Client waits for server response; blocking call

  • Asynchronous: Client continues execution; server notifies when processing completes


9. What is API versioning?

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


10. What are query parameters vs path parameters?

Answer:

  • Path parameter: Part of URL; identifies resource (/users/123)

  • Query parameter: Optional parameters; filtering, sorting (/users?role=admin)


HTTP & Security

11. What are common HTTP status codes in APIs?

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


12. Difference between authentication and authorization

Answer:

  • Authentication: Verifies identity (username/password, JWT, OAuth token)

  • Authorization: Determines access permissions (roles, scopes)


13. Explain JWT (JSON Web Token)

Answer:

  • Token-based stateless authentication mechanism

  • Contains header, payload, and signature

  • Server validates signature; payload contains user claims (id, roles)

  • Example: Authorization: Bearer <token>


14. Difference between OAuth 2.0 and OAuth 1.0

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


15. What is CORS (Cross-Origin Resource Sharing)?

Answer:

  • Browser security feature that blocks requests from different origins

  • Server sends Access-Control-Allow-Origin header to allow requests


16. Difference between HTTP and HTTPS

Answer:

  • HTTP: Unencrypted, insecure

  • HTTPS: SSL/TLS encryption, secure data transfer, authentication of server


17. Explain API throttling and rate limiting

Answer:

  • Prevents abuse by limiting number of requests per client per time window

  • Example: 1000 requests per hour


18. Difference between PUT and PATCH

Answer:

  • PUT: Replaces entire resource

  • PATCH: Modifies only specified fields


19. What is caching in Web APIs?

Answer:

  • Storing responses to reduce server load

  • Implemented via HTTP headers:

    • Cache-Control, ETag, Last-Modified


20. What are idempotent HTTP methods?

Answer:

  • GET, PUT, DELETE are idempotent

  • POST is not idempotent


Design Patterns & Best Practices

21. Best practices for designing REST APIs

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


22. What is HATEOAS and why is it important?

Answer:

  • Hypermedia links in responses

  • Improves discoverability and self-documenting APIs


23. Explain API documentation best practices

Answer:

  • Use Swagger/OpenAPI

  • Include request/response examples

  • Document authentication and error codes


24. Explain RESTful vs RESTless API

Answer:

  • RESTful: Follows REST constraints (stateless, resource-oriented, standard verbs)

  • RESTless: Violates REST principles (RPC-style, actions in URL)


25. What is API mocking?

Answer:

  • Simulate API responses before backend is ready

  • Tools: Postman, WireMock, Swagger Mock


26. How do you implement pagination?

Answer:

  • Query params: /users?page=2&limit=20

  • Use offset and limit

  • Response can include total count, next/prev links


27. Difference between synchronous and asynchronous APIs in practice

Answer:

  • Synchronous: /login returns token immediately

  • Asynchronous: /report triggers processing, client polls /report/status


28. Explain API versioning strategies

Answer:

  • URI-based: /v1/users

  • Header-based: Accept: application/vnd.myapi.v1+json

  • Query parameter: /users?version=1

  • Allows backward compatibility


29. Explain API gateway pattern

Answer:

  • Single entry point for all API calls

  • Handles authentication, rate limiting, logging, request routing


30. Difference between REST and GraphQL

Answer:

Feature REST GraphQL
Data fetching Fixed endpoints Flexible queries
Overfetching Possible No overfetching
Versioning Needed Not needed
Complexity Simple Higher learning curve

Error Handling

31. How do you handle errors in Web APIs?

Answer:

  • Standard HTTP status codes

  • Error payload includes: code, message, details

  • Example JSON:

{ "code": 400, "message": "Invalid input", "details": "Email is required" }

32. Difference between client-side and server-side errors

Answer:

  • Client-side (4xx): Bad request, unauthorized, forbidden, not found

  • Server-side (5xx): Internal server error, database failures


33. How to implement global exception handling in APIs

Answer:

  • Middleware or filters (e.g., ASP.NET Core ExceptionFilter, Java Spring @ControllerAdvice)

  • Returns consistent JSON error response


34. Explain optimistic and pessimistic concurrency in APIs

Answer:

  • Optimistic: Assume no conflict; check version/timestamp before update

  • Pessimistic: Lock resource to prevent concurrent edits


35. Difference between API fail-fast and graceful degradation

Answer:

  • Fail-fast: Detect errors immediately, stop processing

  • Graceful degradation: Return partial results or cached data while service partially fails


Performance & Optimization

36. How do you improve API performance?

Answer:

  • Enable caching (HTTP headers, Redis)

  • Use pagination and filtering

  • Compress payloads (gzip)

  • Avoid overfetching

  • Optimize database queries


37. What is throttling and why is it needed?

Answer:

  • Prevent abuse and server overload

  • Limit requests per client (e.g., 1000 per hour)


38. Explain API load balancing

Answer:

  • Distribute requests across multiple instances

  • Ensures high availability and scalability

  • Tools: Nginx, AWS ELB


39. How do you handle large file uploads in APIs?

Answer:

  • Use streaming instead of loading in memory

  • Chunked uploads

  • Limit file size in server configuration


40. How do you secure Web APIs?

Answer:

  • HTTPS for encryption

  • Authentication: OAuth, JWT

  • Authorization: Roles, scopes

  • Rate limiting / throttling

  • Input validation to prevent injections


41. How do you design APIs for enterprise systems?

Answer:

  • Follow RESTful conventions

  • Include versioning

  • Standardized error handling

  • Implement caching, logging, monitoring

  • Ensure scalability and security