Beginner Level: Building Basic Understanding and IQ Fundamentals
Beginner questions focus on core concepts, simple definitions, and IQ-style puzzles to test foundational knowledge. These are ideal for entry-level roles or freshers, emphasizing basic understanding with example data.
- What is a REST API, and how does it differ from a general Web API? A REST API is an architectural style for designing networked applications using HTTP requests to access and manipulate data. It differs from a general Web API (which could use SOAP or GraphQL) by being stateless, cacheable, and using standard HTTP methods like GET, POST. Example: A REST API for a blog might use GET /posts to fetch articles, while a Web API could involve XML-based SOAP for enterprise integrations. Analytical insight: REST promotes simplicity and scalability, making it ideal for mobile apps.
- Explain the key principles of REST architecture. REST principles include statelessness (no client context stored on server), cacheability (responses can be cached), uniform interface (standard methods), and layered system. Example: In a e-commerce API, statelessness means each request to /cart must include authentication tokens. IQ test: Why is statelessness beneficial? It enhances scalability by allowing load balancing without session stickiness.
- What are the main HTTP methods used in REST APIs? GET (retrieve data), POST (create data), PUT (update data), DELETE (remove data), PATCH (partial update). Example data: GET /users/1 returns {"id":1, "name":"John"}. Basic understanding: GET is idempotent and safe, unlike POST which creates new resources.
- What is an endpoint in a REST API? An endpoint is a specific URL path where an API service is available, like /users or /products/123. Example: In a weather app, GET /weather?city=London fetches data. IQ puzzle: Design an endpoint for user login – typically POST /auth/login with body {"username":"user", "password":"pass"}.
- Define idempotency in REST APIs. An operation is idempotent if repeating it yields the same result, like PUT or DELETE. Example: PUT /users/1 {"name":"Alice"} updates once; repeating doesn't change further. Analytical: Non-idempotent POST can create duplicates if retried, causing issues in payment systems.
- What is the role of HTTP status codes in REST? Status codes indicate response outcomes: 200 OK (success), 404 Not Found (resource missing), 500 Internal Server Error. Example: On failed login, return 401 Unauthorized. Basic IQ: Why use 201 Created for POST? It signals new resource creation with location header.
- Explain URI vs. URL in API context. URI (Uniform Resource Identifier) identifies a resource abstractly; URL (Locator) specifies location. Example: URI: users/1; URL: https://api.example.com/users/1. Understanding: URIs enable hypermedia in REST (HATEOAS).
- What is JSON, and why is it preferred in REST APIs? JSON (JavaScript Object Notation) is a lightweight data format. Preferred for readability and parsing ease over XML. Example data: {"product":{"id":1,"price":99.99}}. IQ: Convert XML <user><name>John</name></user> to JSON – {"user":{"name":"John"}}.
- Describe stateless vs. stateful APIs. Stateless: Each request is independent; stateful: Server remembers client state. REST is stateless. Real-life: Stateless APIs scale better in cloud environments like AWS Lambda.
- What is API versioning, and why is it important? Versioning prevents breaking changes, e.g., via URL (/v1/users) or headers. Example: v1 returns basic user data; v2 adds email. Basic: Avoids disrupting existing clients.
- Explain the difference between GET and POST. GET retrieves data (query params); POST submits data (body). Example: GET /search?q=book; POST /books with {"title":"API Guide"}. IQ: Why not use GET for sensitive data? It logs in URLs.
- What are query parameters in REST? Key-value pairs in URL after ?, like /users?age=25&sort=asc. Example data: Filters users over 25 years old.
- Define resource in REST terms. A resource is any data entity, like user or post, accessed via URIs. Example: /orders/456 represents an order resource.
- What is HATEOAS in REST? Hypermedia as the Engine of Application State: Responses include links to related actions. Example: GET /users/1 returns {"name":"John", "links":[{"rel":"posts","href":"/users/1/posts"}]}.
- Explain safe vs. unsafe HTTP methods. Safe: No side effects (GET, HEAD); Unsafe: Modify resources (POST, PUT). Analytical: Safe methods are cacheable.
- What is CORS, and why is it needed? Cross-Origin Resource Sharing allows restricted resources on a web page from another domain. Example: API at api.example.com allows requests from www.client.com via headers.
- Describe API authentication basics. Methods like API keys, Basic Auth. Example: Header Authorization: Basic base64(username:password).
- What is rate limiting in APIs? Limits requests per time window to prevent abuse. Example: 100 requests/hour per IP.
- Explain content negotiation. Client requests format via Accept header; server responds accordingly. Example: Accept: application/json returns JSON.
- What are headers in HTTP requests? Metadata like Content-Type: application/json. Example: User-Agent for client info.
- Define payload in API context. Data sent in request/response body. Example: POST payload {"email":"user@example.com"}.
- What is API documentation? Guides like Swagger/OpenAPI for endpoints. Basic: Ensures usability.
- Explain synchronous vs. asynchronous APIs. Sync: Immediate response; Async: Callback or polling. REST is typically sync.
- What is caching in REST? Store responses for faster access using Cache-Control headers. Example: Cache-Control: max-age=3600.
- Describe error handling basics. Use status codes and error bodies like {"error":"Invalid input"}.
- What is OAuth for APIs? Delegation protocol for access without passwords. Example: Google login for apps.
- Explain path parameters. Variables in URL like /users/{id}. Example: /users/5 fetches user 5.
- What is hypermedia? Links in responses guiding navigation. Example in HATEOAS.
- Define API gateway. Entry point for managing APIs. Basic: Handles routing, auth.
- What are webhooks? Server-to-client callbacks. Example: GitHub push notifications.
- Explain REST vs. SOAP. REST: Lightweight, HTTP; SOAP: Protocol with XML. Analytical: REST better for web.
- What is XML in APIs? Alternative to JSON. Example: <user><id>1</id></user>.
- Describe request body. Data in POST/PUT. Example: JSON object.
- What is response time in APIs? Latency from request to response. Basic: Optimize for user experience.
- Explain idempotent methods again with example. PUT /items/1 {"qty":10} – repeating sets to 10. IQ: Useful for retries.
- What are status code ranges? 1xx info, 2xx success, 3xx redirect, 4xx client error, 5xx server.
- Define client-server architecture in REST. Separation of concerns: Client requests, server responds.
- What is uniform interface? Standard ways to interact with resources.
- Explain layered system principle. Intermediaries like proxies without affecting client/server.
- What is code on demand? Optional: Server sends executable code. Rare in REST.
- Describe basic API testing. Use Postman for GET/POST. Example: Test 200 OK on /health.
- What is API mocking? Simulate APIs for development. Example: Mock server returns fake data.
- Explain API keys. Unique identifiers for auth. Example: Header X-API-Key: abc123.
- What is Bearer token? JWT in Authorization: Bearer <token>.</token>
- Define throttling. Synonym for rate limiting.
- What is pagination? Split large responses, e.g., ?page=1&limit=10.
- Explain filtering in APIs. Query params like ?status=active.
- What is sorting? ?sort=desc on field.
- Describe search in REST. GET /search?q=term.
- What is validation in APIs? Check input data. Example: Ensure email format.
Intermediate Level: Scenario-Based, Real-Life Centric, and Example Data-Oriented
Intermediate questions delve into practical scenarios, data handling, and analytical problem-solving for mid-level roles.
- Scenario: Design a REST API for a todo list app. What endpoints would you create? Endpoints: GET /todos, POST /todos, GET /todos/{id}, PUT /todos/{id}, DELETE /todos/{id}. Example data: POST {"task":"Buy milk","done":false} returns 201 with ID. Real-life: Handle user auth for personal todos.
- How would you handle versioning in a production API without breaking clients? Use URL versioning (/v2/users) or header (Accept: application/vnd.example.v2+json). Scenario: Migrate from v1 (basic fields) to v2 (added phone). Analytical: Header versioning keeps URLs clean but requires client support.
- Explain authentication with JWT in REST APIs. JSON Web Tokens: Client logs in, gets token, sends in headers. Example: Decode token {"sub":"user1","exp":1694000000}. Real-life: Secure microservices communication.
- Scenario: A client complains of slow API responses. How do you diagnose and optimize? Check logs, use profiling tools. Optimize with caching, database indexes. Example: Add Redis cache for GET /products. Analytical: Reduce N+1 queries in ORM.
- What is the difference between PUT and PATCH? Provide a coding example. PUT replaces entire resource; PATCH partial update. Example (JSON): PUT /users/1 {"name":"Bob","age":30}; PATCH /users/1 {"age":31}. Scenario: Use PATCH for bandwidth efficiency in mobile apps.
- How do you implement rate limiting in a REST API? Use middleware like Redis counters. Example: Limit 5 req/min per IP; return 429 Too Many Requests if exceeded. Real-life: Prevent DDoS in public APIs.
- Scenario: Design an API for file uploads. What considerations? POST /uploads with multipart/form-data. Handle large files with streaming. Example: Response {"fileUrl":"https://storage/file.jpg"}. Analytical: Secure against malicious uploads.
- Explain error handling with custom responses. Standardize {"status":400,"message":"Invalid param","details":{}}. Scenario: Validate inputs server-side.
- How does CORS work in practice? Provide code example. Server sets Access-Control-Allow-Origin: . Example (Node.js): res.header("Access-Control-Allow-Origin", ""). Real-life: Enable for frontend-backend separation.
- Scenario: Implement pagination for a large dataset. Use offset/limit or cursor-based. Example: GET /posts?page=2&limit=20 returns links to next/prev. Analytical: Cursor better for infinite scrolling.
- What is API composition, and when to use it? Aggregate multiple APIs into one endpoint. Example: /user-profile combines /users and /posts. Scenario: Reduce client requests in dashboards.
- Explain OAuth 2.0 flows with examples. Authorization Code for web apps; Client Credentials for server-to-server. Example: Redirect to /auth?client_id=abc&scope=read.
- Scenario: Handle concurrent updates in REST. Use optimistic locking with ETag headers. Example: If-Match: "etag-value" on PUT; 412 if mismatch. Real-life: Prevent lost updates in collaborative tools.
- How to secure sensitive data in APIs? Use HTTPS, encrypt payloads. Example: Never log passwords. Analytical: Comply with GDPR.
- What is content negotiation with Accept headers? Client: Accept: application/xml; Server responds in XML if supported. Scenario: Support multiple formats.
- Scenario: Design a search API with filters. GET /products?category=electronics&price_min=100&sort=price_asc. Example data: Returns paginated list.
- Explain webhooks vs. polling. Webhooks: Push notifications; Polling: Client checks periodically. Example: Webhook POST /callback on event.
- How to implement caching strategies? Use ETag for validation, Cache-Control for expiration. Scenario: Cache static data like configs.
- Scenario: API for real-time updates – is REST suitable? REST is stateless; use WebSockets for real-time. But combine: REST for init, WS for updates. Analytical: Chat apps need WS.
- What are common API design anti-patterns? Using POST for everything, poor naming. Example: Avoid /doAction?type=get.
- Explain HATEOAS with a full example. Response: {"data":{...}, "links":[{"rel":"self","href":"/item/1"},{"rel":"delete","href":"/item/1","method":"DELETE"}]}. Scenario: Self-discoverable APIs.
- Scenario: Handle large request bodies. Set limits, use compression. Example: Accept-Encoding: gzip.
- How to monitor API performance? Use tools like Prometheus. Track metrics: latency, error rates.
- Explain API keys vs. tokens. Keys: Static; Tokens: Time-limited. Example: Tokens for sessions.
- Scenario: Design a payment API. POST /payments with idempotency key. Return 202 Accepted for async processing.
- What is schema validation? Use JSON Schema. Example: Validate {"type":"object","properties":{"name":{"type":"string"}}}.
- Explain batch operations in REST. POST /batch with array of requests. Scenario: Bulk updates.
- Scenario: Internationalization in APIs. Accept-Language: en-US; Return localized messages.
- How to handle deprecation? Warn in headers: X-Deprecated: true. Migrate clients.
- What is hypermedia type? Formats like HAL for links. Example: application/hal+json.
- Scenario: API for user roles. Use RBAC; Check permissions per endpoint.
- Explain async APIs with queues. Use RabbitMQ; API accepts, queues job. Return job ID.
- How to test APIs automatically? Use Jest/Supertest. Example: test('GET /users', () => expect(status).toBe(200)).
- Scenario: Handle timeouts. Set server timeouts; Client retries with backoff.
- What is OpenAPI specification? Standard for documenting APIs. Example: YAML file with paths, schemas.
- Explain idempotency keys. Client-generated key for safe retries. Scenario: Payments.
- Scenario: API for graphs/data relationships. Use GraphQL instead, but in REST: Include related data or links.
- How to compress responses? Content-Encoding: gzip if client accepts.
- What are web API best practices? Use nouns for resources, HTTP methods correctly.
- Scenario: Logging in APIs. Log requests/responses without sensitive data.
- Explain conditional requests. If-None-Match for caching. Return 304 Not Modified.
- How to handle file downloads? GET /files/id with Content-Disposition: attachment.
- Scenario: Multi-tenant APIs. Use tenant ID in paths or headers.
- What is API orchestration? Coordinate multiple services. Example: Saga pattern.
- Explain versioning strategies pros/cons. URL: Simple but URL clutter; Header: Clean but complex.
- Scenario: Secure API from injections. Sanitize inputs, use prepared statements.
- How to implement search with Elasticsearch? Proxy requests to ES via API endpoint.
- What is API federation? Combine subgraph APIs.
- Scenario: Handle API evolution. Backward compatibility, feature flags.
- Explain request tracing. Use headers like X-Request-ID for distributed tracing.
Expert Level: Competitive, Coding Examples, Analytical, and IQ Challenges
Expert questions are for senior roles, focusing on complex scenarios, code implementations, and deep analysis.
- Coding: Implement a REST endpoint in Node.js for user creation with validation.
javascript
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) return res.status(400).json({error: 'Missing fields'});
// Save to DB
res.status(201).json({id: 1, name, email});
});
Analytical: Use Joi for advanced validation. Real-life: Prevent SQL injections.
- Scenario: Optimize a high-traffic API suffering from database bottlenecks. Implement read replicas, caching layers like Memcached. IQ: Calculate QPS; Shard DB if needed. Competitive: In exams, discuss CAP theorem trade-offs.
- Explain circuit breakers in API resilience. Pattern to fail fast on downstream failures. Example: Using Hystrix-like libs. Analytical: Prevents cascading failures in microservices.
- Coding: Write a Python Flask endpoint with JWT auth.
python
from flask import Flask, request, jsonify
import jwt
app = Flask(__name__)
@app.route('/protected', methods=['GET'])
def protected():
token = request.headers.get('Authorization').split()[1]
try:
data = jwt.decode(token, 'secret', algorithms=['HS256'])
return jsonify({'message': 'Success', 'user': data['sub']})
except:
return jsonify({'error': 'Invalid token'}), 401
Scenario: Secure admin routes.
- How to implement API gateway with load balancing? Use NGINX or AWS API Gateway. Analytical: Route based on paths, add SSL termination.
- Scenario: Design a distributed system API with eventual consistency. Use CQRS/ES; APIs for commands/queries. IQ: Handle conflicts with version numbers.
- Explain gRPC vs. REST for performance. gRPC uses HTTP/2, protobufs for faster binary. Competitive: Better for internal services.
- Coding: Implement pagination with cursors in Go.
go
package main
import "net/http"
func handler(w http.ResponseWriter, r *http.Request) {
cursor := r.URL.Query().Get("cursor")
limit := 10 // parse from query
// Fetch from DB with cursor
// Return next_cursor in response
}
Analytical: Cursors avoid offset slowness in large datasets.
- What is service mesh in API ecosystems? Infrastructure layer for service communication, e.g., Istio. Real-life: Traffic management.
- Scenario: Handle GDPR compliance in APIs. Add endpoints for data deletion/export. Analytical: Anonymize logs.
- Explain zero-trust security for APIs. Verify every request. Example: Mutual TLS.
- Coding: Async API response in Java Spring. Use @Async or DeferredResult. Example: Return CompletableFuture.
- How to benchmark API performance? Tools like Apache Bench. Measure throughput, latency.
- Scenario: Migrate from monolith to microservices APIs. Strangler pattern: Gradually replace endpoints.
- What is API contract testing? Pact for consumer-driven contracts.
- Coding: Rate limiter in Ruby Sinatra. Use Rack::Attack. Example: throttle('req/ip', limit: 100, period: 3600).
- Explain blue-green deployments for APIs. Switch traffic between versions. Analytical: Zero downtime.
- Scenario: API for machine learning inference. POST /predict with data; Return probabilities. Handle scaling.
- What is backpressure in streaming APIs? Control data flow to prevent overload.
- Coding: HATEOAS in ASP.NET. Add links to models. Example: _links: { self: { href: "/api/item/1" } }.
- How to implement feature toggles in APIs? Config-based; Route to new/old logic.
- Scenario: Secure against API abuse like scraping. CAPTCHA, user-agent checks.
- Explain chaos engineering for APIs. Intentionally inject failures to test resilience.
- Coding: Webhook validation in PHP. Verify signature with HMAC.
- What is API monetization? Usage-based billing. Example: Stripe-like.
- Scenario: Handle schema evolution in APIs. Use protobuf for backward compat.
- Explain mutual authentication. Client and server certs.
- Coding: Batch processing endpoint. Accept array, process in transaction.
- How to use OpenTelemetry for tracing? Instrument code for spans.
- Scenario: API for blockchain integrations. REST wrapper over nodes.
- What is event sourcing in APIs? Store events, replay for state.
- Coding: Conditional PUT with ETag in Express. Check req.headers['if-match'].
- Explain server-sent events (SSE). For real-time push. Alternative to WS.
- Scenario: Design fault-tolerant API. Retries, fallbacks.
- What is API federation with Apollo? Combine GraphQL but adaptable to REST.
- Coding: Compression middleware in Node. Use compression package.
- How to audit API usage? Log all requests, analyze.
- Scenario: International API with currencies. Accept header for locale.
- Explain canary releases. Rollout to subset of users.
- Coding: OAuth client in Python. Use requests-oauthlib.
- What is SPIFFE for identity? Workload identities in services.
- Scenario: API for IoT devices. Lightweight, MQTT over REST.
- Explain adaptive rate limiting. Based on user behavior.
- Coding: Schema validation with Yup. In JS: yup.object().shape({name: yup.string().required()}).
- How to handle long-running requests? Async with polling endpoint.
- Scenario: API governance. Standards enforcement.
- What is RSocket? Reactive protocol over REST.
- Coding: Deprecation warning header. res.set('Warning', '299 - Deprecated').
- Explain API security scanning. Tools like OWASP ZAP.
- Scenario: Scale API to millions of users. CDN, auto-scaling, database optimization. IQ: Discuss trade-offs in consistency vs. availability.
- Bonus Analytical: Compare REST with GraphQL for complex queries. GraphQL reduces over-fetching; REST needs multiple calls. Real-life: Use GraphQL for flexible clients.
- Coding: Implement a simple cache in memory. Use Map in JS for key-response caching.
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam