runtime
301 / 500
question 301 HTTP & API Clients · easy

Build API URLs safely

Every endpoint in a report script builds its URL by hand, and some end up with // or an unencoded space. Write build_url(base, path, params). Join base and path with exactly one /, leave out parameters whose value is None, and encode the rest in the order given; a list value repeats the parameter once per item (type=article&type=preprint). With no parameters left, the URL has no ?.

Functionbuild_url(base, path, params)
base / pathe.g. "https://api.openalex.org/" and "/works"; either may or may not have the slash
paramsa dictionary of values (text, numbers, lists of text, or None)
Returnsthe full URL as text
Examples
callbuild_url('https://api.openalex.org/', '/works', {'search': 'numpy arrays', 'mailto': 'ana@example.com', 'page': None})returns'https://api.openalex.org/works?search=numpy+arrays&mailto=ana%40example.com'
callbuild_url('https://earthquake.usgs.gov/fdsnws/event/1', 'count', {'format': 'geojson', 'minmagnitude': 7})returns'https://earthquake.usgs.gov/fdsnws/event/1/count?format=geojson&minmagnitude=7'
callbuild_url('https://api.openalex.org', 'works', {'type': ['article', 'preprint'], 'per-page': 50})returns'https://api.openalex.org/works?type=article&type=preprint&per-page=50'

Loading your progress…

Build API URLs safely — Python practice · Runtime