A Python interface to the OpenStreetMap Overpass API for querying geographical data
—
The API class provides the main interface for querying the OpenStreetMap Overpass API. It handles query construction, HTTP communication, response parsing, and server status monitoring.
Create an API instance with customizable endpoint, timeout, headers, debugging, and proxy configuration.
class API:
def __init__(self, *args, **kwargs):
"""
Initialize Overpass API client.
Keyword Args:
endpoint (str): URL of overpass interpreter (default: "https://overpass-api.de/api/interpreter")
timeout (Union[int, float, Tuple[int, int]]): TCP connection timeout. If tuple, (connection_timeout, read_timeout) (default: 25)
headers (Dict[str, str]): HTTP headers to include in requests (default: {"Accept-Charset": "utf-8;q=0.7,*;q=0.7"})
debug (bool): Enable debugging output (default: False)
proxies (Dict[str, str]): Dictionary of proxies for requests library (default: None)
"""import overpass
# Basic API instance
api = overpass.API()
# Custom configuration
api = overpass.API(
endpoint="https://overpass.myserver/interpreter",
timeout=60,
debug=True,
proxies={"http": "http://proxy.example.com:8080"}
)Execute Overpass QL queries with flexible response formatting and query building options.
def get(
self,
query: Union[str, MapQuery, WayQuery],
responseformat: str = "geojson",
verbosity: str = "body",
build: bool = True,
date: Union[str, datetime] = ''
) -> Union[Dict, List, str]:
"""
Execute Overpass query and return results.
Args:
query: Overpass QL query string or query object
responseformat: Output format ("geojson", "json", "xml", "csv")
verbosity: Data verbosity level ("ids", "skel", "body", "tags", "meta")
build: Whether to build complete query from template (True) or use raw query (False)
date: Query historical data as of this date (ISO format or datetime object)
Returns:
Query results in specified format:
- geojson: GeoJSON dictionary
- json: JSON dictionary
- xml: XML string
- csv: List of lists
Raises:
OverpassSyntaxError: Query contains syntax errors
TimeoutError: Request timeout occurred
MultipleRequestsError: Multiple simultaneous requests attempted
ServerLoadError: Server is under load
ServerRuntimeError: Server encountered runtime error during query execution
UnknownOverpassError: Unknown error occurred
"""
def search(self, feature_type: str, regex: bool = False):
"""
Search for features (currently not implemented).
Args:
feature_type: Type of feature to search for
regex: Whether to use regex matching
Raises:
NotImplementedError: This method is not yet implemented
"""# Basic query
response = api.get('node["name"="Salt Lake City"]')
# Different response formats
json_response = api.get('node["name"="Springfield"]', responseformat="json")
xml_response = api.get('node["name"="Springfield"]', responseformat="xml")
# CSV format with field specification
csv_response = api.get(
'node["name"="Springfield"]["place"]',
responseformat="csv(name,::lon,::lat)"
)
# Historical query
response = api.get(
'node["name"="Salt Lake City"]',
date="2020-04-28T00:00:00Z"
)
# Raw query (no template building)
raw_response = api.get(
'[out:json][timeout:25];node["name"="Salt Lake City"];out body;',
build=False
)Monitor Overpass API server status and available query slots to optimize request timing.
@property
def slots_available(self) -> int:
"""
Get count of immediately available query slots.
Returns:
Number of available slots (0 means all slots occupied)
"""
@property
def slots_waiting(self) -> Tuple[datetime, ...]:
"""
Get waiting slot availability times.
Returns:
Tuple of datetime objects when waiting slots will become available
"""
@property
def slots_running(self) -> Tuple[datetime, ...]:
"""
Get running slot completion times.
Returns:
Tuple of datetime objects when running slots will be freed
"""
@property
def slot_available_datetime(self) -> Optional[datetime]:
"""
Get next slot availability time.
Returns:
None if slot available now, otherwise datetime when next slot available
"""
@property
def slot_available_countdown(self) -> int:
"""
Get seconds until next slot available.
Returns:
0 if slot available now, otherwise seconds until next slot
"""# Check server status before querying
if api.slots_available > 0:
response = api.get(query)
else:
wait_time = api.slot_available_countdown
print(f"Server busy, wait {wait_time} seconds")
# Monitor server load
print(f"Available slots: {api.slots_available}")
print(f"Next available at: {api.slot_available_datetime}")Deprecated uppercase method names for backward compatibility.
def Get(self, *args, **kwargs):
"""Deprecated: Use get() instead."""
def Search(self, *args, **kwargs):
"""Deprecated: Use search() instead."""SUPPORTED_FORMATS = ["geojson", "json", "xml", "csv"]Available response formats for query results.
Install with Tessl CLI
npx tessl i tessl/pypi-overpass