
This course provides a comprehensive introduction to APIs (Application Programming Interfaces) for beginners. By completion, you will be able to:
An interface is a boundary across which two independent systems meet and interact. Interfaces abstract away implementation details while exposing controlled functionality.
| Interface | Exposed Controls | Hidden Implementation |
|---|---|---|
| Radio | Volume, station, power on/off | Internal circuitry, signal processing |
| Alarm Clock | Volume, station, time setting, alarm | Electronics, radio receiver |
| Remote Control | Power, channel, volume buttons | Infrared/RF signaling, device communication |
Key Principle: You don’t need to understand how something works internally to use it effectively.
A GUI (Graphical User Interface) provides visual elements for user interaction:
Example: A streaming music app’s play button interface:
While UIs (User Interfaces) are designed for end-users, APIs are designed for application programmers to use and extend in their applications.
Example – Button API:
Developer writes: button.onClick = playMusic
API provides: Visual rendering, click detection, sound feedback
Developer doesn't write: Button physics, rendering engine, audio feedbackModern applications use APIs at multiple levels:
Concept: “It’s APIs all the way down” - Abstractions exist at every level from user interface to binary data.
An API (Application Programming Interface) is a contract that:
| Benefit | Description |
|---|---|
| Abstraction | Hide complex implementation details |
| Reusability | Avoid recreating common functionality |
| Standardization | Consistent interfaces across platforms |
| Efficiency | Complex operations in few lines of code |
Programming languages provide APIs for common operations:
String API Example:
Input: "hello".toUpperCase()
Output: "HELLO"File System API:
Web browsers implement standardized Web APIs:
Cross-Browser Compatibility: Code works in Chrome, Firefox, Safari, Edge because they all implement the same web API specifications.
Libraries package code to solve common problems:
Frameworks provide APIs for extending functionality:
An API is a contract between:
The Contract Specifies:
Remote APIs allow control of objects and services over a network, not just locally.
| Use Case | API Function |
|---|---|
| Remote Control | Send commands to TV/radio from distance |
| Robot Control | Send commands, receive sensor data |
| Traffic Signs | Change displays via API calls |
| Drone Control | Control flight via mobile app |
Problem: Local devices have limited storage Solution: Access vast remote databases
Example – Music Recognition:
Example – Google Translate AR:
REST is an architectural style for designing networked applications. It emerged as the dominant standard for web APIs.
Note: While REST is dominant, alternatives exist (e.g., GraphQL) for specific use cases.
APIs that follow REST constraints are called RESTful.
HTTP (HyperText Transfer Protocol) is the foundation of web communication.
| Component | Description |
|---|---|
| URL/URI | Universal Resource Locator/Identifier – address of resource |
| Scheme | Protocol (e.g., https://) |
| Domain | Server location (e.g., api.spotify.com) |
| Path | Specific resource location |
| Query String | Parameters after ? |
GET /users/123 HTTP/1.1
Host: api.example.com
Authorization: Bearer token123
Content-Type: application/json| Method | Purpose | CRUD Operation |
|---|---|---|
| GET | Retrieve data | Read |
| POST | Create new resource | Create |
| PUT | Update entire resource | Update |
| PATCH | Partial update | Update |
| DELETE | Remove resource | Delete |
| Code Range | Meaning | Examples |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created |
| 3xx | Redirection | 301 Moved Permanently |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | Server Error | 500 Internal Server Error |
Headers are key-value pairs in requests and responses:
Request Headers:
Accept: What content type is expectedAuthorization: Authentication credentialsContent-Type: Format of sent dataResponse Headers:
Content-Type: Format of returned dataContent-Length: Size of responseCache-Control: Caching instructionsHTTP is stateless: Each request is independent. The server doesn’t remember previous requests.
Managing State:
For an API to be considered RESTful, it must satisfy these architectural constraints:
Four sub-constraints:
In REST, everything is a resource:
E-book Store Example:
/books → Collection of books
/books/123 → Specific book
/authors → Collection of authors
/authors/456 → Specific author
/authors/456/books → Books by specific authorImage Sharing App Example:
/users → User resources
/users/789/photos → Photos by user
/photos/321/loves → Users who loved photo
/albums → Album resources| Operation | HTTP Method | Endpoint | Description |
|---|---|---|---|
| Create | POST | /authors | Create new author |
| Read | GET | /authors/123 | Get specific author |
| Read All | GET | /authors | Get all authors |
| Update | PATCH | /authors/123 | Update author |
| Delete | DELETE | /authors/123 | Remove author |
JSON is the standard data format for REST APIs:
{
"id": "123",
"name": "Beyoncé",
"followers": 32000000,
"genres": ["pop", "r&b"],
"external_urls": {
"spotify": "https://open.spotify.com/artist/..."
}
}Characteristics:
cURL is a command-line tool for making HTTP requests:
# 2. Basic GET request
curl https://api.example.com/users
# 3. With headers
curl -H "Authorization: Bearer token" \
-H "Accept: application/json" \
https://api.example.com/users
# 4. POST request with data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"John","email":"john@example.com"}' \
https://api.example.com/usersBenefits:
Features:
Features:
Features:
Store sensitive/configuration data separately:
{
"api_key": "your_secret_key",
"base_url": "https://api.example.com",
"account_sid": "ACxxxxx"
}Usage: {{api_key}} or {{base_url}}
Benefits:
SDKs (Software Development Kits) or Helper Libraries wrap HTTP calls in native language constructs.
| Benefit | Description |
|---|---|
| Abstraction | No manual HTTP request construction |
| Native Feel | Code looks like native language |
| Error Handling | Built-in error management |
| Authentication | Automatic credential management |
| Documentation | IDE autocomplete and tooltips |
Raw HTTP (cURL):
curl -X POST https://api.twilio.com/2010-04-01/Accounts/ACxxx/Messages.json \
--data-urlencode "To=+1234567890" \
--data-urlencode "From=+1987654321" \
--data-urlencode "Body=Hello World" \
-u ACxxx:auth_tokenWith Helper Library (Node.js):
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: '+1234567890',
from: '+1987654321',
body: 'Hello World'
});Most API calls are asynchronous (non-blocking):
// Promise-based
client.messages.list()
.then(messages => {
messages.forEach(msg => console.log(msg.body));
})
.catch(error => console.error(error));
// Async/await
async function getMessages() {
try {
const messages = await client.messages.list();
return messages;
} catch (error) {
console.error(error);
}
}Simple key passed in header or query parameter:
Header: X-API-Key: your_api_keyToken-based authentication (OAuth 2.0):
Header: Authorization: Bearer eyJhbGciOiJ...Username and password (base64 encoded):
Header: Authorization: Basic dXNlcjpwYXNz| Practice | Reason |
|---|---|
| Never commit credentials | Prevent credential leaks in version control |
| Use environment variables | Keep secrets out of code |
| Rotate tokens regularly | Limit exposure if compromised |
| Use HTTPS only | Encrypt data in transit |
| Implement rate limiting | Prevent abuse |
Never expose API keys in client-side code:
// BAD: Keys visible in browser source
const API_KEY = "sk_live_1234567890";
// GOOD: Server-side proxy
// Client → Your Server → External APISolution: Use server-side proxy to keep keys secure.
Webhooks are “reverse APIs” - instead of you calling the API, the API calls you.
| Scenario | Webhook Action |
|---|---|
| Incoming SMS | Twilio POSTs message data to your URL |
| Payment received | Stripe sends payment confirmation |
| Git push | GitHub triggers CI/CD pipeline |
| New email | Email service notifies your app |
Your endpoint must return appropriate response:
// Twilio expects TwiML (Twilio Markup Language)
const twiml = new MessagingResponse();
twiml.message('Thanks for your submission! π·');
response.writeHead(200, {'Content-Type': 'text/xml'});
response.end(twiml.toString());Photo Collection App (“Pickle” - Pick Your Pics):
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β User Phone ββββββΆβ Twilio Number ββββββΆβ Webhook Handlerβ
β (Sends Photo) β β (Receives MMS) β β (Processes SMS)β
βββββββββββββββββββ ββββββββββββββββββββ ββββββββββ¬βββββββββ
β
βΌ
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Web Browser βββββββ Vue.js App βββββββ API Endpoint β
β (Views Gallery)β β (Displays Pics) β β (Serves JSON) β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββexports.handler = function(context, event, callback) {
const twiml = new MessagingResponse();
// Log incoming message
console.log(`Received: ${event.Body}`);
// Send thank you response
twiml.message('Thanks for your submission! π·');
callback(null, twiml);
};exports.handler = async function(context, event, callback) {
const client = context.getTwilioClient();
const gallery = [];
// Fetch messages from Twilio API
const messages = await client.messages.list({
to: context.TWILIO_NUMBER
});
// Process each message and extract media
for (const message of messages) {
const media = await message.media().list();
for (const item of media) {
gallery.push({
src: `https://api.twilio.com${item.uri.replace('.json', '')}`,
description: message.body,
alt: message.body,
thumbnailWidth: 200
});
}
}
callback(null, gallery);
};async loadImages() {
const response = await fetch('/api/pics');
this.gallery = await response.json();
}When designing an API, evaluate against REST constraints:
| Constraint | Implementation | Status |
|---|---|---|
| Client-Server | Separate frontend/backend | β |
| Stateless | No session storage | β |
| Cacheable | Cache headers provided | β |
| Layered System | API calls other APIs | β |
| Uniform Interface | Resource URIs, CRUD operations | β |
| Code on Demand | Not applicable | N/A |
APIs (Application Programming Interfaces) are contracts that enable software systems to communicate. They abstract implementation complexity while exposing controlled functionality.
RESTful APIs leverage HTTP protocols and follow architectural constraints that promote scalability, reliability, and ease of use. By understanding interfaces at all levelsβfrom physical devices to web servicesβyou can build powerful applications that combine multiple services through API integration.
The modern development workflow relies heavily on APIs: consuming third-party services, building your own APIs, and creating seamless integrations that would be impossible to build from scratch.
Final Thought: “APIs are everywhere” - from the buttons in your UI framework to the web services powering your applications. Mastering APIs is essential for modern software development.