Python · Intermediate level

Intermediate level · Module 4: Working with Web APIs · Lesson 2 of 3

Calling APIs with requests

Write Python code that requests data, checks the response and extracts the needed fields.

In this lesson you will

  • Send GET requests with parameters
  • Parse JSON responses into Python data

Key concepts

requests.getparamsresponse.json()raise_for_status()

The lesson

The requests package makes HTTP simple: response = requests.get(url, params={...}, timeout=10). Always set a timeout so your program does not wait forever on a slow connection.

Call response.raise_for_status() to turn error status codes into exceptions, then response.json() to get a Python dictionary. Wrap the call in try/except requests.RequestException to handle network failures gracefully.

Keep API keys out of your code. Read them from an environment variable with os.environ.get('API_KEY') so they are never shared by accident when you publish your code.

Step by step

  1. Install requests in your venv.
  2. Request exchange rates with a timeout.
  3. Check the status and parse the JSON.
  4. Print the rates you need, or a clear error message if the request fails.

Practice activity

Write a script that fetches currency exchange rates from a public API and prints the USD rate for a list of currencies.

Expected result: A script that prints the requested rates or a clear error.

Check your understanding

  1. Why always pass a timeout to requests.get?

    Show answer

    Without it a request on a poor connection can hang indefinitely.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.