CSS Prepare

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

BasisTypes
By accessPublic/open (anyone, often with a key), Partner (selected businesses), Private/internal (within an organization), Composite (combines several calls)
By contextWeb APIs, library/framework APIs, operating-system APIs (Windows API, POSIX), browser APIs (DOM, Fetch, Geolocation, Web Storage)
By style/protocolREST, SOAP, GraphQL, gRPC, WebSocket, RPC (XML-RPC/JSON-RPC)

3. REST (Representational State Transfer)

Architectural style defined by Roy Fielding (2000). Constraints:

  1. Client–server separation
  2. Stateless — each request carries all needed information
  3. Cacheable responses
  4. Uniform interface — resources identified by URIs, manipulated via representations (JSON), self-descriptive messages
  5. Layered system — proxies, gateways, load balancers invisible to client
  6. Code on demand (optional) — server can send executable code

Resource-based design with HTTP methods (CRUD mapping)

OperationMethodEndpointSuccess codeIdempotent?
List studentsGET/api/students200 OKYes
Get one studentGET/api/students/42200 OK / 404Yes
Create studentPOST/api/students201 CreatedNo
Replace studentPUT/api/students/42200 / 204Yes
Partially updatePATCH/api/students/42200Not guaranteed
Delete studentDELETE/api/students/42204 No ContentYes

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

PointSOAPREST
TypeProtocol (W3C standard)Architectural style
FormatXML only (SOAP envelope)JSON, XML, HTML, text
ContractWSDL describes the service strictlyOptional (OpenAPI/Swagger)
TransportHTTP, SMTP, othersHTTP
StateCan be statefulStateless
SecurityWS-Security built inHTTPS + OAuth/JWT
PerformanceHeavierLighter, cacheable
UseBanking, enterprise, formal contractsPublic 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.
MeasureRESTGraphQL
Requests3 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 returnedFull objects (over-fetching): about 15 KBOnly the requested fields: about 4 KB
ResultSlower, more bandwidthAbout 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.