API Interview Questions
API Interview Questions
1. What is an API?
Definition: An API (Application Programming Interface) is a set of rules and protocols that
allows different software applications to communicate with each other.
Real-time Scenario:
Whenyou use a weather app on your phone, it doesn't have weather data built-in. Instead, it calls
a weather service API(like OpenWeatherMap), sends your location, and receives current
weather data to display.
Real-time Scenario:
Afooddeliveryappuses REST APIs:
Real-time Usage:
GET /api/products #Get all products (E-commerce site)
POST /api/cart # Add item to cart
PUT /api/users/123 # Update user profile
DELETE /api/comments/5 # Remove comment
PATCH /api/orders/10 # Update order status partially
POST:
5. What is an endpoint?
Real-time Example:
Banking Application:
GET /api/accounts →List all accounts
GET /api/accounts/{id} →Get specific account
POST /api/transfers →Initiate money transfer
GET /api/transactions →View transaction history
7. What is JSON?
Definition: JSON (JavaScript Object Notation) is a lightweight data interchange format that's
easy for humans to read and write, and easy for machines to parse.
Real-time Scenario:
Whenyoufilloutaregistration form, your data is converted to JSON:
{
"firstName": "Sarah",
"lastName": "Chen",
"email": "sarah@[Link]",
"phone": "+1234567890",
"address": {
"street": "123 Main St",
"city": "San Francisco",
"zipcode": "94107"
}
}
Real-time Examples:
200 OK - Your request succeeded (Google search results)
404 Not Found - Page doesn't exist (broken link)
500 Internal Server Error - Website is down
403 Forbidden - You're not allowed to access (admin panel without login)
Client Errors:
Server Errors:
/products
GET /products →Returns list of products
POST
/products/{id} →Create new product (admin)
GET
/products/{id} PATCH →Get specific product details
PUT
/products/{id} DELETE →Update entire product
/products/{id} →Update product price only
→Remove product
Definition: Each request from client to server must contain all the information needed to
understand and process the request. Server doesn't store any client context between requests.
Real-time Example:
When you browse products on Amazon:
Real-time Scenario:
TestingpaymentAPIsfor success, failure, load, and edge cases.
• Postman
• Swagger/OpenAPI
• SoapUI
Example:
{
"content": "Just launched my new app!",
"privacy": "public"
}
Perfect
I’ll clearly explain each question (16–30) with:
• Simple definition
• Real-time example
•
•
Interview-friendly explanation
Practical usage
Real-time Example
When a user opens a dashboard after login:
GET /api/user/profile
Authorization: Bearer eyJhbGciOiJIUzI1Ni...
Content-Type: application/json
Accept: application/json
Interview Tip
Headers are mainly used for authentication, content type, caching, and client
information.
Real-time Examples
[Link] JSON data
Content-Type: application/json
{
"email": "user@[Link]",
"password": "123456"
}
2. File upload
Content-Type: multipart/form-data
Why it is important
If the server receives JSON but
Content-Typeis missing or wrong, the request may fail or
throw errors.
Interview Tip
The Acceptheader tells the server which response format the client expects.
Real-time Example
Mobile App Request
GET /api/products
Accept: application/json
Server responds:
{
"id": 101,
"name": "Laptop",
"price": 50000
}
Browser Request
Accept: text/html
• category=mobile → Filter
• price=low →Sort
• page=2 →Pagination
Interview Tip
Query parameters are optional and mainly used for filters and search conditions.
Interview Tip
Mandatory Yes No
Real-time Example
GET /api/users/10?active=true
Real-time Examples
Interview Tip
Real-time Scenario
Benefits
✔ Interactive testing
✔ Auto-generated docs
✔ Client SDK generation
24. What is versioning in API?
Definition
API versioning is the practice of
maintaining multiple versions of an API to support changes
without breaking existing clients.
Real-time Example
/api/v1/users →Old mobile apps
/api/v2/users →New mobile apps
Interview Tip
Real-time Problem
A company changes response format:
Old:
{"name": "John"}
New:
{"fullName": "John Doe"}
1. Client–Server
2. Stateless
3. Cacheable
4. Uniform Interface
5. Layered System
Real-time Example
Frontend React app → Backend Node API → Database
Each layer works independently.
Interview Tip
Backend:
[Link]
Server sends:
Access-Control-Allow-Origin: [Link]
Interview Tip
• Protocol
• Domain
• Port
Real-time Example
Blocked:
[Link] → [Link]
✔ Allowed:
[Link] → [Link]
API authentication verifies who is making the request before allowing access.
GET /api/data?api_key=abc123
Authentication = identity
Authorization = permissions
Definition:
JWTis acompact, URL-safe token used to securely transmit information between client and
server.
Why JWT is used:
• Stateless authentication
• No server-sidesession storage
• Scales easilyinmicroservices
Real-time Scenario:
Userlogsintoane-commerce site → receives JWT → uses it to access orders, cart, and profile.
Details:
Example Payload:
{
"userId": 123,
"role": "admin",
"exp": 1700000000
}
GET /api/orders
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Why “Bearer”?
Whoeverholdsthe token can access the resource — so it must be protected.
OAuthis anauthorization framework that allows third-party apps to access user data without
exposing passwords.
Real-time Scenario:
“Login with Google”:
• App never sees your Google password
• Google issues an access token
• App accesses profile/email with permission
Definition:
A refresh token is usedto obtain a new access token without requiring the user to log in again.
Real-time Scenario:
Restricts thenumberof API requests a client can make within a specific time window.
Real-time Example:
100 requests per minute per user
Why needed:
• Preventabuse
• Protectserver resources
• Ensurefair usage
Real-time Problem:
A public API withoutlimits gets:
• Bot attacks
• DDoS attempts
•
Server crashes
Solution:
Return:
429 Too Many Requests
Definition:
Anoperationis idempotent if performing it multiple times produces the same result.
Idempotent Methods:
• GET
• PUT
• DELETE
Not Idempotent:
Definition:
Paginationdivides large datasets into smaller chunks to improve performance.
Real-time Scenario:
Instagramfeed:
Alternative Approaches:
• Offset-based pagination
• Cursor-based pagination (better for large datasets)
"orderId": 123,
"status": "shipped",
"links": {
"track": "/orders/123/track",
"cancel": "/orders/123/cancel"
}
}
• Authentication
• Rate limiting
• Routing
• Logging
• User Service
• Order Service
• Payment Service
•
Inventory Service
• Bankingsystems
• Enterprise legacy systems
GraphQLisa query language that allows clients to request exactly the data they need.
Real-time Example:
{
user(id: 1){
name
email
}
}
Definition:
Temporarycontrol over request rates when server load is high.
Real-time Example:
Definition:
Distributesincomingrequests across multiple servers.
Real-time Scenario:
Definition:
SimulatingAPI responses without actual backend.
Real-time Usage:
Frontendteamworks before backend is ready.
58. What is Contract Testing?
Definition:
Real-time Example:
Frontend expects email field → backend must not remove it.
Impact:
Highlatency = poor user experience.
• Caching
• Database indexing
• CDN
•
Async processing
Perfect
Hereisthe final continuation – SECTION 3 (Q61–Q100) in the same detailed, definition +
elaboration + real-time scenario + interview-ready style.
• HTTPS (SSL/TLSencryption)
• Authentication(JWT, OAuth, API Keys)
• Authorization(Role-based access)
• Input validation
• Rate limiting
• Firewall & WAF
Step-by-step Flow:
1. User entersusername/password
2. Client sendsrequest → POST /login
3. Server validatescredentials
4. Server generatesJWT
5. Token returnedtoclient
6. Client sends tokenin future requests
7. Server verifiestoken
Real-time Example:
Amazon,Netflix,Gmaillogin flows.
Definition:
Returningmeaningful responses when something fails.
Best Practices:
• Proper HTTPstatus codes
• Clear error messages
• Logging errors
• Not exposinginternal stack traces
Example Response:
{
Definition:
Handlingallapplication errors in one place (middleware/global handler).
Benefits:
• Cleanercode
• Consistent error responses
• Easierdebugging
Real-time Use:
[Link] errormiddleware
Spring Boot global exception handler
Best Practices:
Good Design:
GET /users
POST /users
GET /users/{id}
Bad Design:
/getUsers
/createUser
Definition:
Ensuresincomingrequests match expected structure.
Why important:
• Preventsinvalid data
• Improvessecurity
• Avoidscrashes
Tools:
• Joi
• Zod
• JSON Schema
• OpenAPI validation
Definition:
Astandardformat to define REST APIs.
Uses:
• Auto-generate documentation
• Generate client SDKs
• Validate requests
Real-time Example:
SwaggerUIforStripe,GitHub, PayPal.
Definition:
Codeexecuted between request and response.
Real-time Uses:
• Authentication
• Logging
• Validation
• Error handling
• Rate limiting
Flow:
Request → Middleware → Controller → Response
Scenario:
/api/orders:
Everyrequest to
1. Verify JWT
2. Log request
3. Validate input
4. Process request
Definition:
Fileuploadsuse multipart/form-data.
Real-time Example:
Uploadingprofilepicture to Facebook/Instagram.
Headers:
Content-Type: multipart/form-data
Techniques:
• Pagination
• Streaming
• Compression (gzip)
• Caching
• Lazy loading
Real-time Scenario:
Downloading transaction history from a bank.
Definition:
TrackingAPI performance, uptime, and failures.
Metrics:
• Response time
• Error rate
• Traffic volume
• Availability
Common Tools:
• New Relic
• Datadog
• Prometheus
• Grafana
• ELK Stack
Definition:
A webhookisa way for a server to send real-time data to another system automatically when an
event occurs.
Difference from API:
• Payment success
• Payment failure
• Refund processed
• Order placed
• User registered
• Payment completed
Used in microservices.
Why used:
• Improves scalability
• Prevents blocking
• Handles traffic spikes
• RabbitMQ
• Kafka
• AWS SQS
• Redis Queue
Real-time Example:
OrderprocessinginAmazon.
Synchronous Asynchronous
Client waits Client continues
Blocking Non-blocking
Slower forheavy tasks Better for scalability
Example:
Definition:
Retryingfailed APIrequests automatically.
Real-time Scenario:
Definition:
Stopssending requeststo failing service to prevent system collapse.
Real-time Example:
Techniques:
• Idempotency keys
• Request hashing
• Unique transaction IDs
Example:
Prevent double payment when user clicks “Pay” twice.
Definition:
Managingchanges to API without breaking clients.
Techniques:
• Versioning
• Backward compatibility
• Optional fields
Logging Includes:
• Timestamp
• Endpoint
• Status code
• Response time
• User ID
• Errors
Why important:
• Debugging
• Auditing
• Monitoring
Definition:
Misuse ofAPI intentionally or unintentionally.
Examples:
• Brute force attacks
• Scraping
• DDoS
• Excessive requests
Prevention:
• Ratelimiting
• Captcha
• Authentication
Techniques:
• Inputvalidation
• Preparedstatements
• ORM
• Escapinginputs
Bad Example:
"SELECT * FROM users WHERE id=" + userInput
Definition:
Maximumtime a client waits for response.
Real-time Example:
Payment API timeoutafter 30 seconds.
Techniques:
• Asyncprocessing
• Threadpools
• Queues
• Locks
• Optimistic concurrency control
Real-time Example:
Multipleusersbooking same seat in a train.
Definition:
Deployingnew version without downtime.
Flow:
Definition:
Graduallyreleasing new API version to small % of users.
Benefit:
Detectbugsbefore full rollout.
Tools:
• Postman automation
• Jest
• Mocha
• Newman
• RestAssured
Types:
• Unit tests
• Integration tests
• Load tests
92. What is Schema Registry?
Definition:
Centralrepository for API schemas.
Used in:
• Microservices
• Event-driven systems
• Swagger/OpenAPI
• Examples
• Sample requests/responses
• Error scenarios
• Authentication guide
• PayPal Sandbox
• Stripe Test Mode
96. What is Rate Limit Exceeded Error?
Definition:
HTTP Code:
429 Too Many Requests
• Logs
• Monitoring
• Distributed tracing
• Alerts
• Error tracking (Sentry)
Real-time Example:
Client → APIGateway → Auth Service → Order Service → Payment Service
• Better collaboration
• Clear contracts
• Parallel development
• Better scalability
1. Endpoint: POST/login
2. Input validation 3.
Authenticateuser 4.
Generate JWT 5.
Return token 6.
Secure storage 7.
Error handling 8.
Logging 9. Rate
limiting
Sample Response:
{
"token": "eyJhbGciOiJIUzI1NiIs...",
"expiresIn": 900,
"user": {
"id": 101,
"name": "Mounika"
}
}