Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 12 / Topic 2 of 11

What an API and a REST API are

An API (Application Programming Interface) is a way for one program to ask another program for data or actions. A web API does it over HTTP: you send a request to a URL and get JSON back, not a web page. Think of a bank's ATM: you do not walk into the vault, you use the buttons the bank gives you.

A REST API is a common style of web API:

  • Each kind of thing is a resource with its own URL (an endpoint): /api/products, /api/orders.
  • The HTTP method says the action: GET /api/products/1 reads product 1, DELETE /api/products/1 removes it.
  • Data goes back and forth as JSON.

Reading API docs

Before you write code, read the API's docs and find these five things:

Question Example answer (Open-Meteo weather API)
Base URL https://api.open-meteo.com
Endpoint and method GET /v1/forecast
Query parameters latitude, longitude, daily, timezone, forecast_days
Authentication None needed (many APIs need a key)
Response shape and limits JSON with a daily object; a free daily request limit

Query parameters

Query parameters are the key=value options after ?. Do not glue them together by hand: spaces, & and โ‚น must be encoded (turned into URL-safe text). urlencode does that.

from urllib.parse import urlencode

params = {"q": "tea & coffee", "city": "New Delhi"}
print("https://shop.example.com/search?" + urlencode(params))
# https://shop.example.com/search?q=tea+%26+coffee&city=New+Delhi

API keys: keep secrets out of your code

An API key is a secret password for your program. The server uses it to know who is calling and to count your requests. It is usually sent in a header. Never write a real key in your code: code gets shared, pushed to GitHub and copied. Keep it in an environment variable (a named value your operating system gives to programs, Part 7) and read it with os.environ.

export WEATHER_API_KEY="abc123"        # macOS/Linux (for this terminal only)
set WEATHER_API_KEY=abc123             # Windows cmd
import os

api_key = os.environ.get("WEATHER_API_KEY")
if api_key is None:
    print("Please set the WEATHER_API_KEY environment variable")

๐Ÿ” Going deeper: many projects keep keys in a .env file that is listed in .gitignore, and load it with the third-party python-dotenv package.

Done here? The practice set for Part 12 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide