optional · CSS study notes
I.17 Application Program Interface (API)
⬆️ Back to: P-I.I. Introduction to Computing
🧭
Page Outline — click a heading to jump.
🎯
Exam pattern (2016–2026): Not asked directly. Useful for "insecure APIs" in 2019 Q5(a) cloud security (see I.29) and for Web Engineering.
CSS Computer Science (Optional) — Paper-I, Section-A, Topic I, p.40. Covers: Application Program Interface (API).
Definition
An API is a defined set of rules, protocols, and tools that allows one piece of software to communicate with another — it specifies how software components should interact, without exposing the internal implementation details of either side.
Key Characteristics
- Acts as a contract: defines what requests can be made, what data format to use, and what responses to expect
- Abstraction: the calling program doesn't need to know how the API's underlying function works internally — only what it does and how to call it
- Enables modularity and reuse: developers can build on existing services (e.g., a weather API) instead of building that functionality from scratch
Common Types of APIs
- Web APIs: accessed over the Internet using HTTP, typically returning data in JSON or XML.
- How it works: a client sends an HTTP request to a server's API endpoint (a URL); the server processes it and sends back a structured response.
- Examples: a weather-service API returning forecast data, a payment-gateway API processing a transaction.
- Advantage/disadvantage: lets independently built systems exchange data over standard web protocols with no shared codebase; performance depends on network conditions and the API depends on the provider staying available/unchanged.
- Operating System APIs: allow applications to request services directly from the OS.
- How it works: exposes system calls/functions for tasks such as file access, memory allocation, process management, and display rendering — an application calls the API instead of manipulating hardware directly.
- Examples: the Windows API (Win32), POSIX API on Unix/Linux systems.
- Advantage/disadvantage: gives applications safe, consistent access to hardware/OS resources without needing to know low-level hardware details; ties the application to that OS's specific API, which is why cross-platform software needs OS-specific handling or an abstraction layer.
- Library/Framework APIs: the set of functions/classes a programming library or framework exposes for other code to use.
- How it works: a developer calls pre-written functions (e.g., a drawing function in a graphics library) instead of writing that functionality from scratch; the library handles the implementation internally.
- Examples: a graphics library's drawing functions, a math library's statistical functions.
- Advantage/disadvantage: saves development time and leverages tested, optimized code; introduces a dependency on that library's version and continued support.
- REST API: a widely used web API design style based on standard HTTP methods operating on resources identified by URLs.
- How it works: resources (e.g., a user record, a product) are addressed by URL, and standard HTTP methods act on them — GET (retrieve), POST (create), PUT (update/replace), DELETE (remove); each request is stateless, carrying all information needed to process it.
- Examples: most modern social-media, e-commerce, and cloud-service APIs are REST-based.
- Advantage/disadvantage: simple, stateless, and scalable, making it the dominant style for web services; being stateless means the client must resend context (e.g., authentication tokens) with every request.
Why APIs Matter (Exam Angle)
- APIs let independently developed software systems interoperate without either needing to know the other's internal source code
- They are central to modern software architecture — mobile apps, websites, and cloud services are largely built by combining calls to multiple APIs
- A good API design principle: expose only what's necessary, hide internal complexity (information hiding — the same principle as encapsulation in OOP)
MCQ Traps
- An API is not software itself — it's a specification/interface for software to communicate; don't confuse it with an application.
- A REST API operates over HTTP using standard methods (GET/POST/PUT/DELETE) — a commonly tested detail.
- REST APIs are stateless — each request must carry all context needed (e.g., authentication) since the server does not remember prior requests; a frequently tested distinguishing feature.
- An OS API is not the same as a Web API — an OS API is called locally by a program to access system resources, while a Web API is called over a network using HTTP.
✅ Self-Test Questions (with Answers)
Q1. Define an API and explain why abstraction is central to its purpose.
Ans: An Application Programming Interface (API) is a defined set of rules, protocols and tools that specifies how one piece of software may request services from another — what calls can be made, in what format the arguments must be supplied, and what response will be returned. It is best understood as a contract between a provider and a consumer of functionality. Abstraction is central because the API deliberately exposes only the what and hides the how: the caller learns the function signature and behaviour but never sees the internal algorithm, data structures or source code behind it. Three consequences make this essential:
- Reduced complexity — a developer can call a payment API in one line without understanding card-network settlement.
- Implementation independence — the provider can rewrite or optimise the internals entirely, and existing client code keeps working so long as the interface is unchanged.
- Reuse and modularity — teams build on tested services (weather, maps, SMS gateways) rather than rewriting them.
Note the standard MCQ trap: an API is not an application; it is the interface specification through which applications communicate.
Q2. Name one type of API and one HTTP method commonly used in a REST API.
Ans: One well-known type is the Web API, which is accessed over the Internet using HTTP/HTTPS and typically returns data encoded in JSON or XML; a real example is the Google Maps API or a bank's payment-gateway API. Other recognised types are Operating System APIs (the Win32 API on Windows, the POSIX API on Unix/Linux), library/framework APIs, and database APIs such as JDBC or ODBC.
A commonly used HTTP method in a REST API is GET, which retrieves a representation of a resource without modifying it. The four core REST methods map to the CRUD operations:
- GET — Read: retrieve a resource (safe and idempotent).
- POST — Create: submit new data, creating a subordinate resource.
- PUT — Update/Replace: replace the resource at a known URL (idempotent).
- DELETE — Delete: remove the resource (idempotent).
PATCH performs a partial update. Typical status codes to quote are 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found and 500 Internal Server Error. HTTP runs on port 80 and HTTPS on port 443.
Q3. How does an API relate to the OOP principle of information hiding/encapsulation?
Ans: They are the same underlying idea applied at different scales. Encapsulation in object-oriented programming bundles data and the methods that operate on it inside a class, and information hiding restricts outside access to a deliberately small public surface — declaring fields private and exposing only public methods. An API is precisely that public surface, raised from the level of a single class to the level of a whole library, service or system: the published operations are the public methods, and everything else — internal data structures, algorithms, database schema — is private. The shared benefits follow directly:
- Loose coupling — the caller depends only on the published interface, not on internal detail.
- Safe evolution — internals can be refactored or replaced without breaking clients, so long as the contract holds.
- Integrity protection — state can only be changed through validated operations, not by arbitrary direct access.
A useful exam formulation: "An API is encapsulation applied at the system boundary rather than the class boundary." The design maxim in both cases is to expose only what is necessary and hide the rest.
Q4. Distinguish between an OS API and a Web API, giving one example of each.
Ans: An Operating System API is invoked locally, by a program running on the same machine, to request services from the kernel — file access, memory allocation, process creation, device and display handling. The call is essentially a function call into system libraries, executed in microseconds, with no network involved. A Web API is invoked remotely across a network, normally over HTTP/HTTPS, by sending a request to a URL endpoint on a server that may be anywhere in the world; latency is measured in milliseconds and the call can fail for purely network reasons.
| Aspect | OS API | Web API |
|---|---|---|
| Location of callee | Same machine (kernel / system libraries) | Remote server over a network |
| Transport | System calls / local function calls | HTTP or HTTPS (ports 80 / 443) |
| Data format | Native language data types, memory pointers | JSON or XML text payloads |
| Typical latency | Microseconds | Milliseconds, network dependent |
| Failure modes | Permission denied, invalid handle, out of memory | Timeout, 404, 500, rate limiting, provider outage |
| Coupling | Tied to one operating system | Language and platform independent |
| Example | Win32 API on Windows; POSIX on Linux | Google Maps API; a bank payment gateway API |
Because an OS API ties a program to one platform, cross-platform software either writes OS-specific code paths or uses an abstraction layer such as the Java Virtual Machine or a portable runtime.
Q5. What does it mean for a REST API to be "stateless," and why does this matter for scalability?
Ans: Statelessness means the server stores no client session context between requests. Every request must be self-contained — it carries all the information needed to process it, including authentication credentials (typically a token in an Authorization header), the target resource and any parameters. The server treats each request as if it were the first it had ever seen from that client; request N+1 gains nothing from request N. Application state is held by the client, while the server holds only resource state in its database.
This matters enormously for scalability:
- Horizontal scaling is trivial. Since no server holds session data, a load balancer can route each request to any server in the pool. Adding capacity is simply a matter of starting more identical servers.
- No session replication cost. In a stateful design, session data must be pinned to one server ("sticky sessions") or replicated across all of them — both add memory overhead and complexity that grows with user count.
- Fault tolerance. If a server crashes mid-traffic, no session is lost; the next request is simply handled elsewhere.
- Cacheability. Self-contained, side-effect-free GET responses can be cached by intermediaries and CDNs, cutting load on the origin server.
The trade-off is redundancy on the wire: the client must resend its token and context with every call, increasing per-request payload size and requiring authentication to be re-validated each time.
CSS angle: Pakistan's digital-economy infrastructure rests on exactly this model — NADRA's identity-verification services, the SBP-regulated Raast instant payment system, and branchless-banking platforms such as Easypaisa and JazzCash all expose APIs so that banks, telecoms, FBR and provincial e-governance portals can interoperate without sharing codebases. Open, well-documented public-sector APIs are a recognised prerequisite for the Digital Pakistan agenda.