Home / GIS and Open Map Data for Beginners

How to Use OpenStreetMap in Python: OSMnx, Overpass, and Nominatim With Real Code

A close-up view of a laptop screen showing a coding and data analysis software interface

Photo: Daniil Komov / Pexels

OpenStreetMap in a browser is a map. OpenStreetMap in Python is a dataset with an API, and the difference is the whole reason to learn it: streets become networks you can route on, buildings become rows in a table, and a city's worth of features lands in a dataframe in one line. This guide builds the stack in the order a project actually grows: OSMnx first for instant results, Overpass when you need to say exactly what you want, Nominatim for addresses, and the raw OSM API last, for reading the database itself. The data you are querying is introduced in open map data; the same data inside a desktop GIS is how to use openstreetmap data.

Interactive tool

The Python OSM Stack: Build Order

Check off each step as you finish it. Your progress stays on this page.

0 of 6 complete

0% done

Start With OSMnx: One Line to a Real Dataset

Install with pip install osmnx (it brings GeoPandas and NetworkX with it) and the canonical first call is:

```

import osmnx as ox

place = ox.geocode_to_gdf("Berkeley, California")

pois = ox.features_from_place("Berkeley, California", tags={"amenity": "cafe"})

graph = ox.graph_from_place("Berkeley, California", network_type="drive")

```

Three ideas carry the whole library. features_from_place (and its sibling features_from_bbox, which takes a bounding box when a place name is the wrong shape) returns a GeoDataFrame of whatever the tags describe: buildings, parks, hospitals, benches, every mapped thing, with its OSM tags as columns. graph_from_place returns a street network as a NetworkX graph, ready for shortest paths, centrality, and the other network questions. And everything is just GeoPandas underneath, so filtering, joining, and plotting use the skills you already have. Plot the first result before believing it, as the checklist insists: a map on screen catches the wrong Berkeley (there are several) faster than any table.

Tags: The Vocabulary Every Query Speaks

OSM data is organized by tags, key value pairs on every element: amenity=cafe, highway=residential, building=yes, natural=water. Every tool in this guide filters by tags, so fluency here is the real skill. A feature query is a dict of the tags you want, and an element can carry dozens of tags beyond the one you matched, which is where the analysis gold sits (opening hours, surface, wheelchair access, all unevenly complete, all honestly absent where nobody mapped them). Learn the vocabulary from the data itself: pull a small area, print the columns, and see what your neighborhood's mappers actually record. The tag system is also why OSM beats a shapefile download for questions like "all outdoor seating": the attribute exists because the data model invites it. Our open map database guide explains the element model, nodes, ways, and relations, that the tags hang on.

Overpass API: Full Control, Your Own Queries

When OSMnx's conveniences chafe, drop to the Overpass API, the read only query engine over the full database, and send queries with requests:

```

import requests

q = """

[out:json][timeout:60];

area[name="Berkeley"]->.a;

node"amenity"="cafe";

out center;

"""

r = requests.post("https://overpass-api.de/api/interpreter",

data={"data": q},

headers={"User-Agent": "my-research-script/0.1 (contact: me@example.com)"})

elements = r.json()["elements"]

```

Overpass QL reads as: choose element types (node, way, relation), filter by tags, restrict to an area or bounding box, and say what to output. out center is the working trick for ways and relations, giving each a usable point. Respect the service: set a real User-Agent identifying your script, keep a timeout in the query and the request, cache responses to disk, and never loop a public instance at full speed; for heavy work, run your own instance or use a commercial mirror. OSMnx itself is an Overpass client, so this section is not a rival stack, it is the layer underneath, and reading its queries teaches you QL for free. The sibling intent, using the OSM API from Python generally, is this same stack; the API proper is the next section.

A laptop displaying code on a wooden desk, in a dimly lit workspace
A laptop displaying code on a wooden desk, in a dimly lit workspace

Nominatim: Addresses to Coordinates, Politely

For geocoding, names and addresses to coordinates and back, call Nominatim:

```

import requests

r = requests.get("https://nominatim.openstreetmap.org/search",

params={"q": "Berkeley City Hall", "format": "json", "limit": 1},

headers={"User-Agent": "my-research-script/0.1 (contact: me@example.com)"})

lat, lon = r.json()[0]["lat"], r.json()[0]["lon"]

```

The usage policy is the content here, not a footnote: at most one request per second, a valid identifying User-Agent is required (requests without one are blocked), results must be cached rather than re queried, and bulk geocoding belongs on your own instance. The geopy library wraps Nominatim in a friendlier object if you geocode often. Keep the returned place class and bounding box with your result, the same match quality discipline as how to find coordinates by address teaches for every geocoder.

The Raw OSM API: Reading the Database Itself

The main OSM API (api.openstreetmap.org, API 0.6) serves individual elements and map extracts by bounding box as XML:

```

import requests

r = requests.get("https://api.openstreetmap.org/api/0.6/map",

params={"bbox": "-122.28,37.86,-122.26,37.88"},

headers={"User-Agent": "my-research-script/0.1"})

```

Its bounding box calls are size capped, so this is a scalpel for small areas and single elements (fetch one node, way, or relation by ID to inspect its full tag set and history), not a bulk download path; bulk belongs to planet extracts and regional files from download services, the territory of openstreetmap download. Parse the XML with xml.etree or hand it to shapely via a small converter when you need geometries. Editing through this API requires OAuth and a changeset workflow that is a project of its own; reading is open, and reading is what analysis needs. If your goal shifts from analysis to contributing, how to add a place to openstreetmap is the human scale on ramp.

From Query to Map: Plotting and Saving Results

Data in a dataframe is halfway to value; the last mile is a picture and a file. OSMnx results plot directly (ox.plot_graph for networks, GeoDataFrame .plot() for features), and a two line plot is the fastest sanity check in the whole workflow, because a wrong city, a clipped bounding box, or an empty tag filter all announce themselves visually. For real maps, export and style in QGIS, or build the figure in matplotlib with the dataframe's geometry. Save results in a format that keeps the geometry honest: GeoPackage (df.to_file with driver GPKG) for GIS work, GeoJSON for web tools, and never a plain CSV of coordinates when the features are lines or polygons, because a cafe point survives CSV and a river does not. Record, in the filename or a notes file, the query, the date, and the area: OSM data changes daily under its contributors' hands, and a result you cannot re run is a result you cannot defend. Reproducibility is the difference between a script and a screenshot, and it costs one text file.

Routing and Analysis: Where the Stack Pays Off

The reason to pull streets as a graph rather than as lines on a map is the analysis that follows, and OSMnx makes the canonical moves short. A shortest path is ox.shortest_path between the graph nodes nearest to your origin and destination points (ox.nearest_nodes does the snapping), and its length is a sum over edge attributes, in meters, ready to compare against the driven world. Centrality, the question of which intersections a city actually flows through, is a NetworkX call away on the same graph. For features, the GeoDataFrame invites spatial questions in plain GeoPandas: count the cafes within a polygon, join buildings to the parcels or neighborhoods that contain them with a spatial join, buffer a river and ask what falls inside. None of this needs new concepts beyond the earlier sections: tags chose the data, Overpass fetched it, GeoPandas and NetworkX think about it. The honest caveat rides along: results inherit the map's completeness, which varies by neighborhood and by feature type, so an analysis of benches is a sample of mapped benches. State that in any write up, and the work is both useful and defensible.

Related Guides

If this page answered part of the question, these GIS and open map data guides cover the rest of the same ground:

Frequently Asked Questions

What is the easiest way to get OpenStreetMap data into Python?

OSMnx. pip install osmnx, then features_from_place or features_from_bbox for a GeoDataFrame of mapped features, or graph_from_place for a routable street network. It handles the Overpass queries, the geometry assembly, and the projections for you, and everything it returns is standard GeoPandas.

Is using OpenStreetMap in Python free?

Yes. The libraries are open source and the public services (Overpass, Nominatim, the OSM API) are free within their usage policies: identify your script with a real User-Agent, respect rate limits (Nominatim allows one request per second), and cache results. Heavy or commercial volume belongs on your own instance or a paid mirror.

What is the difference between Overpass and the OSM API?

Overpass is a read only query engine over the whole database: filter by tags and area and get exactly the features you describe. The main OSM API serves individual elements and small bounding box extracts, and is also the editing interface. Analysis starts with Overpass (usually through OSMnx); the API is for inspecting specific elements.

How do I geocode addresses in Python with OpenStreetMap?

Call Nominatim's search endpoint with the address and a proper User-Agent, or use geopy's Nominatim wrapper. Keep the returned match class with each result, cache responses, and stay within one request per second on the public service. For a spreadsheet scale job, use a batch approach or your own instance.

Can I use OpenStreetMap data commercially from Python?

Yes. The data is licensed under the ODbL: you may use it commercially with attribution to OpenStreetMap contributors, and share alike applies to databases you derive and distribute. Crediting contributors in your app or paper is a license condition, not a courtesy.

Photo credits: Daniil Komov (Pexels); Daniil Komov (Pexels). Photos are served from this site; follow the credit to the library page for the original.