Lesson 6: Working with APIs

⏱ ~35 min Lesson 6 of 14 💚 Free

An API (Application Programming Interface) lets your Python program talk to the internet — fetch weather data, get random jokes, look up stock prices, or send messages. APIs are how modern applications connect to services.

Key Concepts

What Is an API?

An API is a way for software to request services from another system. You send an HTTP request to a URL (endpoint). The server returns data (usually JSON). Your code reads the JSON.

HTTP Requests with requests

import requests
response = requests.get('https://api.example.com/data')
data = response.json()
response.status_code == 200 means success. 404 = not found. 500 = server error.

Query Parameters

Pass data to an API:
params = {'city': 'Tulsa', 'units': 'imperial'}
response = requests.get(url, params=params)
This appends ?city=Tulsa&units=imperial to the URL automatically.

API Keys

Most real APIs require an API key — a secret token that identifies you. Never put API keys directly in your code. Use environment variables or a .env file (and never commit them to git!).

✅ Check Your Understanding

1. What does an API response typically contain?

2. What does a status code of 200 mean?

3. Why should API keys never be committed to git?