optional · CSS study notes
17. API (Application Programming Interface)
CSS Optional — Paper-II, Section-B · P-II.VI.17 · APIs connect front ends, back ends and third-party services. Expect definitions, REST vs SOAP, HTTP methods and status codes.
1. Definition
- An API is a defined set of rules and interfaces through which one software component requests services or data from another, without knowing its internal implementation.
- Analogy: a restaurant menu and waiter — you order from the menu (API specification); the waiter (API) carries the request to the kitchen (server) and returns the dish (response).
- A web API is an API accessed over HTTP(S), usually exchanging JSON or XML.
2. Types of APIs
| Basis | Types |
|---|---|
| By access | Public/open (anyone, often with a key), Partner (selected businesses), Private/internal (within an organization), Composite (combines several calls) |
| By context | Web APIs, library/framework APIs, operating-system APIs (Windows API, POSIX), browser APIs (DOM, Fetch, Geolocation, Web Storage) |
| By style/protocol | REST, SOAP, GraphQL, gRPC, WebSocket, RPC (XML-RPC/JSON-RPC) |
3. REST (Representational State Transfer)
Architectural style defined by Roy Fielding (2000). Constraints:
- Client–server separation
- Stateless — each request carries all needed information
- Cacheable responses
- Uniform interface — resources identified by URIs, manipulated via representations (JSON), self-descriptive messages
- Layered system — proxies, gateways, load balancers invisible to client
- Code on demand (optional) — server can send executable code
Resource-based design with HTTP methods (CRUD mapping)
| Operation | Method | Endpoint | Success code | Idempotent? |
|---|---|---|---|---|
| List students | GET | /api/students | 200 OK | Yes |
| Get one student | GET | /api/students/42 | 200 OK / 404 | Yes |
| Create student | POST | /api/students | 201 Created | No |
| Replace student | PUT | /api/students/42 | 200 / 204 | Yes |
| Partially update | PATCH | /api/students/42 | 200 | Not guaranteed |
| Delete student | DELETE | /api/students/42 | 204 No Content | Yes |
Example request and response
POST /api/students HTTP/1.1
Host: university.edu.pk
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
{ "name": "Ali Khan", "program": "BSCS" }
HTTP/1.1 201 Created
Location: /api/students/43
Content-Type: application/json
{ "id": 43, "name": "Ali Khan", "program": "BSCS" }
Calling an API from JavaScript
fetch("https://api.example.com/weather?city=Karachi")
.then(res => res.json())
.then(data => console.log(data.temperature))
.catch(err => console.error(err));
4. SOAP vs REST
| Point | SOAP | REST |
|---|---|---|
| Type | Protocol (W3C standard) | Architectural style |
| Format | XML only (SOAP envelope) | JSON, XML, HTML, text |
| Contract | WSDL describes the service strictly | Optional (OpenAPI/Swagger) |
| Transport | HTTP, SMTP, others | HTTP |
| State | Can be stateful | Stateless |
| Security | WS-Security built in | HTTPS + OAuth/JWT |
| Performance | Heavier | Lighter, cacheable |
| Use | Banking, enterprise, formal contracts | Public web and mobile APIs |
GraphQL (Facebook, 2015): one endpoint; the client specifies exactly which fields it needs — avoids over-fetching and under-fetching.
5. API Security and Management
- Authentication: API keys, OAuth 2.0 (delegated access — "Log in with Google"), JWT (signed tokens).
- HTTPS always; input validation; rate limiting (e.g. 100 requests/minute → 429 Too Many Requests).
- Versioning (
/api/v1/), documentation (OpenAPI/Swagger), API gateways, monitoring.
6. Real Examples
Google Maps API (embed maps, geocoding), payment-gateway APIs (cards, mobile wallets), SMS gateway APIs (OTP), weather APIs, social login APIs, courier-tracking APIs, government verification APIs.
🎯 CSS Exam Angle
Definition + analogy → types table → REST constraints → CRUD/HTTP-method table → a sample request/response → SOAP vs REST table. This covers every likely API question.
⚠️ MCQ Traps
- REST is a style, SOAP is a protocol.
- POST is not idempotent; GET, PUT and DELETE are.
- 201 = created; 204 = success with no content; 429 = too many requests.
- WSDL is for SOAP; OpenAPI/Swagger documents REST APIs.
- REST requires statelessness — no server-side session per client.
✅ Self-Check (with Answers)
Q1. Define API with an everyday example.
Ans: A set of rules letting one program request services from another without knowing its internals. Example: a travel site uses an airline's API to fetch flight availability and prices.
Q2. Design REST endpoints for a library's books resource.
Ans: GET /api/books (list), GET /api/books/{id} (one), POST /api/books (create), PUT /api/books/{id} (replace), PATCH /api/books/{id} (update), DELETE /api/books/{id} (delete).
Q3. What does "stateless" mean in REST and why is it useful?
Ans: The server keeps no client session between requests; each request contains all needed information (e.g. an auth token). This lets any server handle any request, simplifying load balancing and scaling.
Q4. Why is POST not idempotent but PUT is?
Ans: Repeating a POST creates a new resource each time (two orders); repeating a PUT with the same data sets the resource to the same state, so the result is unchanged.
Q5. When would you choose SOAP over REST?
Ans: In enterprise or financial integrations needing a strict WSDL contract, built-in WS-Security, reliable messaging or distributed transactions, or when integrating with existing SOAP-based systems.
📜 Past-Paper Questions & MCQs (CSS 2016–2026)
2024 · Paper-II · Q8(c) · 6 marks
Q. Create a numerical comparison of the efficiency of data exchange using different APIs such as REST and GraphQL. Discuss the considerations in choosing the appropriate API for a given scenario.
Ans.
- Scenario: a mobile screen shows a user's name, their last 5 post titles and the comment count of each post.
| Measure | REST | GraphQL |
|---|---|---|
| Requests | 3 or more (/users/1, /users/1/posts, /posts/{id}/comments ...) | 1 (one query to a single endpoint) |
| Round-trip delay (100 ms each) | About 300 ms (sequential) | About 100 ms |
| Data returned | Full objects (over-fetching): about 15 KB | Only the requested fields: about 4 KB |
| Result | Slower, more bandwidth | About 3 times faster and about 70% less data |
{ user(id: 1) { name posts(last: 5) { title commentCount } } }
- Choosing the API:
- REST: simple resources, easy HTTP caching (CDN), mature tooling and a low learning curve. Good for public, cacheable and CRUD APIs.
- GraphQL: complex or nested data, many client types (mobile and web) with different data needs, and rapid frontend change. Costs: harder caching, a more complex server, the N+1 query problem and the need for query-cost limits and security controls.
- Also consider: team skills, performance and bandwidth limits (mobile), versioning, monitoring and security.