foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand what APIs are and how they work
  • Learn HTTP fundamentals and request methods
  • Explore REST API concepts and principles
  • Understand API documentation and endpoints

Introduction to APIs and HTTP

Introduction

Imagine you're at a restaurant. You don't go into the kitchen and cook your own meal - you give your order to the waiter, who communicates with the kitchen staff, and eventually brings you your food. In the world of software, APIs work similarly. They provide a clean interface for different software systems to communicate and exchange information without needing to understand each other's internal workings.

In this lesson, we'll explore the fundamental concepts of APIs and HTTP, the protocol that powers the web. Understanding these building blocks will prepare you to work with any web service or API you encounter.


What Are APIs?

An API (Application Programming Interface) is like a waiter in a restaurant - it's the intermediary that takes your requests and delivers responses from the system you're trying to access.

The Restaurant Analogy

You (Client) → Waiter (API) → Kitchen (Server/Service)
  • You make a request: "I'd like a burger"
  • The waiter translates your request and passes it to the kitchen
  • The kitchen prepares the burger
  • The waiter brings back your food (response)

Types of APIs

Type Description Example
Web APIs Accessed over HTTP Twitter API, Google Maps API
Library APIs Functions in programming libraries Python's requests library
Operating System APIs System-level services Windows API, POSIX API
Hardware APIs Device interfaces Camera API, Bluetooth API

Why APIs Matter

  • Modularity: Systems can be built and updated independently
  • Scalability: Services can handle millions of requests
  • Security: Controlled access to resources
  • Innovation: Developers can build on existing services

HTTP Fundamentals

HTTP (HyperText Transfer Protocol) is the foundation of data communication on the web. Think of it as the postal service that delivers letters (requests) and packages (responses) between computers.

HTTP Request Structure

Every HTTP request contains:

GET /api/users/123 HTTP/1.1
Host: api.example.com
User-Agent: MyApp/1.0
Accept: application/json
Authorization: Bearer token123

HTTP Response Structure

Every HTTP response contains:

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 123
Date: Wed, 12 Dec 2023 10:30:00 GMT

{"id": 123, "name": "John Doe", "email": "john@example.com"}

HTTP Methods (Verbs)

Method Purpose Safe? Idempotent? Example
GET Retrieve data Yes Yes Get user profile
POST Create new resource No No Create new user
PUT Update/replace resource No Yes Update user profile
PATCH Partial update No No Update user email
DELETE Remove resource No Yes Delete user account
HEAD Get headers only Yes Yes Check if resource exists
OPTIONS Get allowed methods Yes Yes Check API capabilities

HTTP Status Codes

Status codes indicate the result of your request:

Range Category Examples
200-299 Success 200 OK, 201 Created, 204 No Content
300-399 Redirection 301 Moved Permanently, 302 Found
400-499 Client Error 400 Bad Request, 401 Unauthorized, 404 Not Found
500-599 Server Error 500 Internal Server Error, 502 Bad Gateway

REST API Principles

REST (Representational State Transfer) is an architectural style for designing web services. Think of it as a set of guidelines for building well-behaved web APIs.

REST Constraints

  1. Client-Server Architecture: Clear separation between client and server
  2. Stateless: Each request contains all necessary information
  3. Cacheable: Responses can be cached to improve performance
  4. Uniform Interface: Consistent way to interact with resources
  5. Layered System: Architecture can be composed of layers
  6. Code on Demand (optional): Server can send executable code

REST Resource Concept

In REST, everything is a resource that can be identified by a URL:

/api/users          # Collection of users
/api/users/123      # Specific user
/api/users/123/posts # User's posts
/api/posts?author=123 # Filtered posts

RESTful URL Design

Resource GET POST PUT DELETE
/users List users Create user Bulk update Delete all users
/users/123 Get user 123 Error Update user 123 Delete user 123

API Documentation

Good API documentation is crucial for developers. It explains how to use the API effectively.

Common Documentation Elements

  • Base URL: The root URL for all API endpoints
  • Authentication: How to authenticate requests
  • Endpoints: Available URLs and their purposes
  • Parameters: Required and optional parameters
  • Request/Response Examples: Sample requests and responses
  • Error Codes: Possible error responses and their meanings
  • Rate Limits: Usage restrictions and limits

OpenAPI Specification

OpenAPI (formerly Swagger) is a standard for documenting REST APIs:

openapi: 3.0.0
info:
  title: User Management API
  version: 1.0.0
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

API Authentication

Most APIs require authentication to control access and track usage.

Common Authentication Methods

Method Description Example
API Key Simple key passed in headers X-API-Key: abc123
Bearer Token JWT or similar token Authorization: Bearer eyJ...
Basic Auth Username/password encoded Authorization: Basic dXNlcjpwYXNz
OAuth Delegated authorization Complex token exchange flow

Rate Limiting

APIs often limit how many requests you can make:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200

Real-World API Examples

Weather API

# Conceptual example - we'll implement this in the next lesson
import requests

# API endpoint
url = "https://api.weatherapi.com/v1/current.json"

# Parameters
params = {
    "key": "your_api_key",
    "q": "London"
}

# Make request
response = requests.get(url, params=params)

# Process response
if response.status_code == 200:
    data = response.json()
    print(f"Temperature in London: {data['current']['temp_c']}°C")

Social Media API

# Twitter API example
# GET /2/users/by/username/:username

url = "https://api.twitter.com/2/users/by/username/python"
headers = {
    "Authorization": "Bearer YOUR_BEARER_TOKEN"
}

response = requests.get(url, headers=headers)
user_data = response.json()

E-commerce API

# Product catalog API
# GET /api/products?category=electronics&limit=10

url = "https://api.store.com/products"
params = {
    "category": "electronics",
    "limit": 10,
    "sort": "price"
}

response = requests.get(url, params=params)
products = response.json()

API Design Best Practices

Resource Naming

  • Use nouns, not verbs: /users not /getUsers
  • Use plural nouns: /users not /user
  • Use lowercase with hyphens: /user-profiles not /user_profiles

HTTP Status Code Usage

  • 200 OK: Successful GET, PUT, PATCH
  • 201 Created: Successful POST
  • 204 No Content: Successful DELETE
  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Missing/invalid authentication
  • 403 Forbidden: Valid auth but insufficient permissions
  • 404 Not Found: Resource doesn't exist
  • 500 Internal Server Error: Server-side error

Versioning

  • URL versioning: /api/v1/users
  • Header versioning: Accept: application/vnd.api.v1+json
  • Query parameter: /users?version=1

Key Points to Remember

  • APIs provide clean interfaces for software systems to communicate
  • HTTP is the protocol that powers web APIs with methods like GET, POST, PUT, DELETE
  • REST is an architectural style for designing web services using resources and standard HTTP methods
  • API endpoints are specific URLs that provide access to API functionality
  • Documentation is essential for understanding how to use an API effectively
  • Authentication controls access to API resources
  • Status codes communicate the result of API requests

Now that you understand the fundamentals of APIs and HTTP, we'll dive into making actual HTTP requests using Python. You'll learn how to interact with real APIs, handle responses, and work with different types of data formats.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service