/
Tech-study-notes

API

Course Overview

This course provides a comprehensive introduction to APIs (Application Programming Interfaces) for beginners. By completion, you will be able to:

Prerequisites

Understanding Interfaces

What is an Interface?

An interface is a boundary across which two independent systems meet and interact. Interfaces abstract away implementation details while exposing controlled functionality.

Physical Interface Examples

InterfaceExposed ControlsHidden Implementation
RadioVolume, station, power on/offInternal circuitry, signal processing
Alarm ClockVolume, station, time setting, alarmElectronics, radio receiver
Remote ControlPower, channel, volume buttonsInfrared/RF signaling, device communication

Key Principle: You don’t need to understand how something works internally to use it effectively.

Graphical User Interfaces (GUI)

A GUI (Graphical User Interface) provides visual elements for user interaction:

Example: A streaming music app’s play button interface:

Application Programming Interfaces (API)

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 feedback

Layered API Architecture

Modern applications use APIs at multiple levels:

  1. Application Framework API (e.g., Android/iOS UI components)
  2. Media Player API (e.g., system audio services)
  3. Web API (e.g., streaming data over network)
  4. Hardware API (e.g., audio drivers)

Concept: “It’s APIs all the way down” - Abstractions exist at every level from user interface to binary data.

API Fundamentals

Definition

An API (Application Programming Interface) is a contract that:

Core Benefits

BenefitDescription
AbstractionHide complex implementation details
ReusabilityAvoid recreating common functionality
StandardizationConsistent interfaces across platforms
EfficiencyComplex operations in few lines of code

Types of APIs

Language APIs

Programming languages provide APIs for common operations:

String API Example:

Input: "hello".toUpperCase()
Output: "HELLO"

File System API:

Web APIs

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.

Library/Framework APIs

Libraries package code to solve common problems:

Frameworks provide APIs for extending functionality:

API as Contract

An API is a contract between:

The Contract Specifies:

  1. What operations are available
  2. What inputs are required
  3. What outputs will be returned
  4. How to handle errors

Remote APIs

Concept

Remote APIs allow control of objects and services over a network, not just locally.

Examples of Remote APIs

Use CaseAPI Function
Remote ControlSend commands to TV/radio from distance
Robot ControlSend commands, receive sensor data
Traffic SignsChange displays via API calls
Drone ControlControl flight via mobile app

Benefits of Remote APIs

Data Access

Problem: Local devices have limited storage Solution: Access vast remote databases

Example – Music Recognition:

Computational Power

Example – Google Translate AR:

REST: Representational State Transfer

REST is an architectural style for designing networked applications. It emerged as the dominant standard for web APIs.

  1. Clear structure for resource interaction
  2. Built on HTTP - leverages existing web infrastructure
  3. Stateless - each request contains all necessary information
  4. Universal - works across all platforms and languages

Note: While REST is dominant, alternatives exist (e.g., GraphQL) for specific use cases.

RESTful APIs

APIs that follow REST constraints are called RESTful.

Web Fundamentals Refresher

HTTP Protocol

HTTP (HyperText Transfer Protocol) is the foundation of web communication.

Key Components

ComponentDescription
URL/URIUniversal Resource Locator/Identifier – address of resource
SchemeProtocol (e.g., https://)
DomainServer location (e.g., api.spotify.com)
PathSpecific resource location
Query StringParameters after ?

HTTP Request Structure

GET /users/123 HTTP/1.1
Host: api.example.com
Authorization: Bearer token123
Content-Type: application/json

HTTP Methods (Verbs)

MethodPurposeCRUD Operation
GETRetrieve dataRead
POSTCreate new resourceCreate
PUTUpdate entire resourceUpdate
PATCHPartial updateUpdate
DELETERemove resourceDelete

HTTP Response Status Codes

Code RangeMeaningExamples
2xxSuccess200 OK, 201 Created
3xxRedirection301 Moved Permanently
4xxClient Error400 Bad Request, 401 Unauthorized, 404 Not Found
5xxServer Error500 Internal Server Error

Headers

Headers are key-value pairs in requests and responses:

Request Headers:

Response Headers:

Statelessness

HTTP is stateless: Each request is independent. The server doesn’t remember previous requests.

Managing State:

RESTful API Constraints

The RESTful Scavenger Hunt

For an API to be considered RESTful, it must satisfy these architectural constraints:

βœ… 1. Client-Server Architecture

βœ… 2. Stateless

βœ… 3. Cacheable

βœ… 4. Layered System

βœ… 5. Uniform Interface

Four sub-constraints:

  1. Resource Identification: Resources identified by URIs
  2. Resource Manipulation through Representations: Clients manipulate resources via representations
  3. Self-descriptive Messages: Each message includes enough information to describe how to process it
  4. Hypermedia as the Engine of Application State (HATEOAS): Responses include links to related resources

β­• 6. Code on Demand (Optional)

Working with REST APIs

Resources

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 author

Image Sharing App Example:

/users              → User resources
/users/789/photos   → Photos by user
/photos/321/loves   → Users who loved photo
/albums             → Album resources

CRUD Operations via HTTP

OperationHTTP MethodEndpointDescription
CreatePOST/authorsCreate new author
ReadGET/authors/123Get specific author
Read AllGET/authorsGet all authors
UpdatePATCH/authors/123Update author
DeleteDELETE/authors/123Remove author

JSON: JavaScript Object Notation

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:

API Exploration Tools

cURL

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/users

Benefits:

API Client Applications

REST Fox (Lightweight)

Features:

Postman (Enterprise)

Features:

Thunder Client (VS Code Extension)

Features:

Environment Variables

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:

Helper Libraries & SDKs

Concept

SDKs (Software Development Kits) or Helper Libraries wrap HTTP calls in native language constructs.

Benefits

BenefitDescription
AbstractionNo manual HTTP request construction
Native FeelCode looks like native language
Error HandlingBuilt-in error management
AuthenticationAutomatic credential management
DocumentationIDE autocomplete and tooltips

Example: Twilio Helper Library

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_token

With Helper Library (Node.js):

const client = require('twilio')(accountSid, authToken);

client.messages.create({
  to: '+1234567890',
  from: '+1987654321',
  body: 'Hello World'
});

Asynchronous Operations

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);
  }
}

Authentication & Security

Common Authentication Methods

API Keys

Simple key passed in header or query parameter:

Header: X-API-Key: your_api_key

Bearer Tokens

Token-based authentication (OAuth 2.0):

Header: Authorization: Bearer eyJhbGciOiJ...

Basic Authentication

Username and password (base64 encoded):

Header: Authorization: Basic dXNlcjpwYXNz

Security Best Practices

PracticeReason
Never commit credentialsPrevent credential leaks in version control
Use environment variablesKeep secrets out of code
Rotate tokens regularlyLimit exposure if compromised
Use HTTPS onlyEncrypt data in transit
Implement rate limitingPrevent abuse

Client-Side Security Concern

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 API

Solution: Use server-side proxy to keep keys secure.

Webhooks: Reverse APIs

Concept

Webhooks are “reverse APIs” - instead of you calling the API, the API calls you.

How Webhooks Work

  1. You register a URL endpoint with the service
  2. When an event occurs, the service sends an HTTP request to your URL
  3. Your application processes the incoming data

Use Cases

ScenarioWebhook Action
Incoming SMSTwilio POSTs message data to your URL
Payment receivedStripe sends payment confirmation
Git pushGitHub triggers CI/CD pipeline
New emailEmail service notifies your app

Webhook Response

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());

Building a Complete API Application

Project Architecture

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)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Components

Incoming Message Handler (Webhook)

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);
};

API Endpoint (Data Provider)

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);
};

Frontend Integration

async loadImages() {
  const response = await fetch('/api/pics');
  this.gallery = await response.json();
}

Data Flow

  1. User sends photo via SMS to Twilio number
  2. Twilio webhook triggers your function
  3. Function stores/processes the submission
  4. User visits website and Vue app loads
  5. Vue fetches data from your API endpoint
  6. Gallery displays user-submitted photos

API Design Considerations

RESTful Evaluation

When designing an API, evaluate against REST constraints:

ConstraintImplementationStatus
Client-ServerSeparate frontend/backendβœ…
StatelessNo session storageβœ…
CacheableCache headers providedβ­•
Layered SystemAPI calls other APIsβœ…
Uniform InterfaceResource URIs, CRUD operationsβ­•
Code on DemandNot applicableN/A

Key Takeaways

  1. APIs abstract complexity - You don’t need to know implementation details
  2. REST is the dominant standard for web APIs
  3. Resources are central - Everything is a resource with a URI
  4. HTTP verbs matter - Use GET, POST, PUT, DELETE appropriately
  5. JSON is the lingua franca - Standard data exchange format
  6. Security is critical - Never expose credentials, use HTTPS
  7. Tools help exploration - cURL, Postman, REST Fox for testing
  8. Helper libraries simplify - Use SDKs when available
  9. Webhooks enable real-time - Event-driven architecture
  10. Constraints provide benefits - REST constraints enable scalability

Additional Resources

Tools Mentioned

Services Used

Key Concepts to Explore Further

  1. OAuth 2.0 authentication flows
  2. GraphQL as REST alternative
  3. API versioning strategies
  4. Rate limiting and throttling
  5. API documentation (OpenAPI/Swagger)
  6. WebSocket APIs for real-time data
  7. Serverless architecture
  8. Microservices and API gateways

Summary

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.