Skip to content

Module 16 · External Libraries and APIs — topic 12 of 12

Working with external data

Getting data from outside your program reliably: downloading and parsing CSV and JSON, cleaning messy values, combining sources, caching downloads, and being a good citizen of other people's servers.

Beginner 10 min read·Lesson 246 of 306 in Python Programming

Learning objectives

  • Combine data from different formats
  • Clean inconsistent values
  • Cache downloads to avoid repeated requests

Definition

External data is information your program obtains from files, websites or APIs that you don't control. Working with it means fetching, validating, cleaning, combining and caching it so the rest of your program can rely on it.

Introduction

Government open data, exchange rates, sports results — external data is everywhere, but it arrives in different formats, with missing values and inconsistent spelling.

Why it matters

Most of the effort in data projects is getting data clean and reliable. Good habits here save hours of debugging wrong results later.

Detailed explanation

A robust pipeline separates steps: fetch the raw data, parse it, clean and validate it, then use it. Keeping raw downloads lets you reprocess without fetching again.

Parse each format with the right tool: csv, json, xml.etree, or pandas for larger tables.

Cleaning means trimming whitespace, normalising case, converting numbers ("1,200", "1.5k"), treating "N/A" and blanks as missing, and fixing date formats.

When combining sources, convert everything to a common structure (for example, a list of dictionaries with the same keys and types).

Cache downloaded data in a file and reuse it; only fetch again when it is missing or too old. This is faster and kinder to the server.

Respect the source: follow rate limits and terms of use, identify your client with a User-Agent where required, and check the data's licence before publishing results.

Validate results: counts, ranges and totals that look wrong usually point to a parsing or cleaning problem.

Syntax

Python
def load(url, cache):
if cache.exists():
return cache.read_text(encoding="utf-8")
text = download(url)
cache.write_text(text, encoding="utf-8")
return text
rows = clean(parse(load(url, cache)))
  • Fetch, parse, clean, use.
  • Cache downloads.
  • Validate results.

Code examples

Combining CSV and JSON sources

Python
import csv
import io
import json
csv_text = "id,name,score\n1,Asha,91\n2,Ravi,78\n"
json_text = '[{"id": 3, "name": "Meera", "score": 85}]'
rows = [{"id": int(r["id"]), "name": r["name"], "score": int(r["score"])}
for r in csv.DictReader(io.StringIO(csv_text))]
rows += json.loads(json_text)
print(sorted(rows, key=lambda r: -r["score"])[0]["name"], len(rows))
Output
Asha 3

Cleaning messy values

Python
raw = [" 1,200 ", "N/A", "950", "", "1.5k"]
def to_number(text):
t = text.strip().lower().replace(",", "")
if not t or t in {"n/a", "na", "-"}:
return None
if t.endswith("k"):
return float(t[:-1]) * 1000
return float(t)
print([to_number(v) for v in raw])
Output
[1200.0, None, 950.0, None, 1500.0]

More examples

Download once, then use the cache

Python
import csv
import io
import threading
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.request import urlopen
class CSVServer(BaseHTTPRequestHandler):
hits = 0
def do_GET(self):
CSVServer.hits += 1
body = "city,temp\nPune,31\nDelhi,36\nChennai,33\nPune,29\n".encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/csv; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), CSVServer)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_port}/temps.csv"
def fetch(url, cache_file):
path = Path(cache_file)
if path.exists():
return path.read_text(encoding="utf-8"), "cache"
with urlopen(url, timeout=5) as resp:
text = resp.read().decode("utf-8")
path.write_text(text, encoding="utf-8")
return text, "network"
for _ in range(2):
text, source = fetch(url, "temps.csv")
print("loaded from", source)
by_city = defaultdict(list)
for row in csv.DictReader(io.StringIO(text)):
by_city[row["city"]].append(int(row["temp"]))
print({city: sum(t) / len(t) for city, t in by_city.items()})
print("server hits:", CSVServer.hits)
server.shutdown()
Output
loaded from network
loaded from cache
{'Pune': 30.0, 'Delhi': 36.0, 'Chennai': 33.0}
server hits: 1

Step-by-step explanation

  • The local server stands in for a website that publishes a CSV file, and counts how often it is asked.
  • The first fetch downloads and saves the file; the second reads the saved copy, so the server is contacted only once.
  • The parsed rows are grouped by city to compute average temperatures.

Expected output

Running “Download once, then use the cache” prints exactly:

TextOutput
loaded from network
loaded from cache
{'Pune': 30.0, 'Delhi': 36.0, 'Chennai': 33.0}
server hits: 1

Practical applications

  • Dashboards built on open government data.
  • Scripts combining exchange rates with local sales figures.

Best practices

  • Keep raw data and clean it in code.
  • Cache downloads and respect rate limits.
  • Validate totals and ranges after cleaning.

Common mistakes

Downloading on every run

Avoid

data = requests.get(url, timeout=10).text # each time the script runs

Prefer

Cache the response in a file and refresh it only when it's stale.

Repeated downloads are slow and can hit rate limits or get you blocked.

Trusting raw values

Avoid

total = sum(float(v) for v in values)

Prefer

total = sum(n for n in map(to_number, values) if n is not None)

One 'N/A' would crash the calculation.

Important notes

  • This completes the External Libraries and APIs module; next are advanced Python concepts.

Key takeaways

  • Fetch, parse, clean, validate, use.
  • Normalise different sources into one structure.
  • Cache downloads and respect data providers.

Try it yourself

  1. 1
    Add an expiry to the cache so data older than one hour is downloaded again.
  2. 2
    Clean a list of messy dates ("27/11/2026", "2026-11-27", "Nov 27 2026") into date objects.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.