Professional WorkflowExtra· 40 min read

Working with APIs, JSON & CSV

Fetch live data from the web with the requests library, read JSON, and save results to a CSV file.

What you will learn

  • Call a web API with the requests library
  • Parse JSON into Python data
  • Read and write CSV files

What is an API?

An API (Application Programming Interface) is a web address that returns data instead of a web page — built for programs, not people. For example, a weather API returns today’s temperature as data your code can use. You send a request to its URL and it sends back a response, usually in JSON format.

JSON (JavaScript Object Notation) is a simple text format for data that looks almost exactly like Python dictionaries and lists — {"name": "Asha", "age": 22}. That close match is why Python and web APIs work so well together.

Fetch data with requests

The most popular tool for calling APIs is the requests library (install it with pip install requests inside your venv). You give it a URL, it fetches the data, and you turn the response into Python objects with .json().

Calling a web API with requests
import requests

response = requests.get("https://api.example.com/users/1")
print(response.status_code)        # 200 means success

data = response.json()             # turn JSON into a Python dict
print(data["name"])

Step by step: requests.get(url) sends a request to the API and returns a response object. response.status_code is a number reporting how it went — 200 means success (you may know 404 for not found). response.json() converts the JSON text into a real Python dictionary, which we then read with data["name"] just like any dict. The API call gives you live data your program can work with.

Note: Output: 200 Asha (The exact data depends on the API you call.)

Watch out: Real network calls can fail — the site may be down or the internet off. Wrap API calls in try/except (you learned this) and check response.status_code before trusting the data.

JSON files: save and load Python data

You can also store data on disk as JSON using the built-in json module. json.dump writes a Python object to a file; json.load reads it back. This is the easiest way to save structured data like a settings file or a saved game.

Saving and loading JSON
import json

user = {"name": "Asha", "age": 22, "skills": ["python", "sql"]}

# write Python -> JSON file
with open("user.json", "w") as f:
    json.dump(user, f)

# read JSON file -> Python
with open("user.json") as f:
    loaded = json.load(f)
print(loaded["skills"])

We start with a normal Python dictionary. json.dump(user, f) converts it to JSON text and writes it into user.json. Later, json.load(f) reads that file and rebuilds the exact same dictionary (and its inner list), so loaded["skills"] gives back ['python', 'sql']. JSON lets your data survive between runs and travel between programs.

Note: Output: ['python', 'sql']

CSV files: rows and columns

A CSV (Comma-Separated Values) file stores table-like data — rows and columns, like a spreadsheet. It is the format you will meet constantly in data work. Python’s built-in csv module reads and writes it safely.

Writing and reading a CSV file
import csv

rows = [["Name", "Score"], ["Asha", 95], ["Ravi", 88]]

# write rows to a CSV file
with open("scores.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

# read it back
with open("scores.csv") as f:
    for row in csv.reader(f):
        print(row)

The rows list holds a header row plus two data rows. csv.writer(f) wraps the file, and .writerows(rows) writes each inner list as one comma-separated line — the file ends up as Name,Score then Asha,95 and so on. To read it back, csv.reader(f) hands us each line as a list of its values, which we print. (The newline="" is the recommended setting that stops blank lines on Windows.)

Note: Output: ['Name', 'Score'] ['Asha', '95'] ['Ravi', '88'] (CSV reads values back as text, so 95 comes back as the string '95'.)

Tip: JSON is best for nested, structured data (objects within objects); CSV is best for flat tables of rows and columns. Knowing both covers the vast majority of everyday data tasks.

Q. What does response.json() do after a requests call?

Answer: response.json() parses the JSON the API returned and gives you back native Python data — usually a dictionary or list — ready to use.

✍️ Practice

  1. Use requests to fetch from a public API and print one field from the JSON.
  2. Write a small list of dictionaries to a JSON file and read it back.

🏠 Homework

  1. Fetch a list of items from a public API, then save selected fields into a CSV file with a header row.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →