Files, JSON, and APIs in Real Projects
Almost every useful Python program reads input from somewhere and sends output somewhere: a CSV on disk, a JSON config, a web API returning data. This lesson covers the everyday patterns for working with files, parsing and producing JSON, and calling APIs safely, the glue of data, AI, and automation scripts.
What You'll Learn
- Reading and writing files the safe way with
with - Parsing and producing JSON
- Calling a web API and handling the response
- Handling failures so a flaky network doesn't crash your job
Files: Always Use with
As you saw in the context managers lesson, with guarantees the file closes even if something fails:
# write
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
# read all lines, one at a time (memory-friendly)
with open("notes.txt") as f:
for line in f:
print(line.strip())
Use mode "w" to overwrite, "a" to append, and the default read mode to read. For data files, looping line by line keeps memory low even on large files.
JSON: The Language of APIs and Config
JSON is how programs exchange structured data. Python's built-in json module converts between JSON text and Python dicts/lists.
import json
# Python object -> JSON text
config = {"model": "classifier", "epochs": 10, "tags": ["v1"]}
text = json.dumps(config, indent=2)
print(text)
# JSON text -> Python object
data = json.loads('{"score": 0.9, "label": "cat"}')
print(data["score"]) # 0.9
For files there are convenient pairs: json.dump(obj, file) writes, json.load(file) reads.
with open("config.json", "w") as f:
json.dump(config, f, indent=2)
with open("config.json") as f:
config = json.load(f)
The 's' versions are for strings; the others go straight to files.
| Criteria | dumps / loads | dump / load |
|---|---|---|
| Works with | Strings in memory | Open file objects |
| Use when | API request/response bodies | Reading/writing JSON files |
dumps / loads
- Works with
- Strings in memory
- Use when
- API request/response bodies
dump / load
- Works with
- Open file objects
- Use when
- Reading/writing JSON files
Calling a Web API
The popular requests library makes HTTP calls readable. Install it into your virtual environment first (pip install requests). A typical GET request:
import requests
resp = requests.get("https://api.example.com/data", timeout=10)
resp.raise_for_status() # raise if the server returned an error code
data = resp.json() # parse the JSON body into a dict
print(data)
Two habits that separate robust code from fragile scripts:
- Always set a
timeout. Without it, a hung server can freeze your program forever. - Always check the status with
raise_for_status()so a 404 or 500 becomes a clear error instead of garbage data flowing downstream.
Sending data with POST, including a JSON body and headers, looks like this:
resp = requests.post(
"https://api.example.com/predict",
json={"text": "hello"}, # serialized to JSON automatically
headers={"Authorization": "Bearer YOUR_KEY"},
timeout=10,
)
resp.raise_for_status()
print(resp.json())
This is exactly the shape of a call to an AI model API: a URL, an auth header, a JSON body, and a JSON response. If you want a full project around this, see Build Your First AI Data App with Python.
Handle Failure Gracefully
Networks fail. Combine what you learned about error handling with these calls:
import requests
def fetch(url):
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
return resp.json()
except requests.Timeout:
print("request timed out")
except requests.HTTPError as e:
print(f"server error: {e}")
except requests.RequestException as e:
print(f"network problem: {e}")
return None
Catching specific requests exceptions lets you retry, skip, or warn, instead of crashing a long automation run on one bad response.
Try It
This runs offline with a fake response so you can practice the JSON shapes you would get back from a real API.
Key Takeaways
- Always read and write files with
withso they close even on error; loop line by line for large files. - Use
json.dumps/json.loadsfor strings andjson.dump/json.loadfor files. - Call APIs with
requests; always set atimeoutand callraise_for_status(). - An AI model API call is just a URL, an auth header, a JSON body, and a JSON response.
- Catch specific
requestsexceptions so network failures don't crash your whole job.

