0
# Core API Interface
1
2
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.
3
4
## Capabilities
5
6
### API Class Initialization
7
8
Create an API instance with customizable endpoint, timeout, headers, debugging, and proxy configuration.
9
10
```python { .api }
11
class API:
12
def __init__(self, *args, **kwargs):
13
"""
14
Initialize Overpass API client.
15
16
Keyword Args:
17
endpoint (str): URL of overpass interpreter (default: "https://overpass-api.de/api/interpreter")
18
timeout (Union[int, float, Tuple[int, int]]): TCP connection timeout. If tuple, (connection_timeout, read_timeout) (default: 25)
19
headers (Dict[str, str]): HTTP headers to include in requests (default: {"Accept-Charset": "utf-8;q=0.7,*;q=0.7"})
20
debug (bool): Enable debugging output (default: False)
21
proxies (Dict[str, str]): Dictionary of proxies for requests library (default: None)
22
"""
23
```
24
25
#### Usage Example
26
27
```python
28
import overpass
29
30
# Basic API instance
31
api = overpass.API()
32
33
# Custom configuration
34
api = overpass.API(
35
endpoint="https://overpass.myserver/interpreter",
36
timeout=60,
37
debug=True,
38
proxies={"http": "http://proxy.example.com:8080"}
39
)
40
```
41
42
### Query Execution
43
44
Execute Overpass QL queries with flexible response formatting and query building options.
45
46
```python { .api }
47
def get(
48
self,
49
query: Union[str, MapQuery, WayQuery],
50
responseformat: str = "geojson",
51
verbosity: str = "body",
52
build: bool = True,
53
date: Union[str, datetime] = ''
54
) -> Union[Dict, List, str]:
55
"""
56
Execute Overpass query and return results.
57
58
Args:
59
query: Overpass QL query string or query object
60
responseformat: Output format ("geojson", "json", "xml", "csv")
61
verbosity: Data verbosity level ("ids", "skel", "body", "tags", "meta")
62
build: Whether to build complete query from template (True) or use raw query (False)
63
date: Query historical data as of this date (ISO format or datetime object)
64
65
Returns:
66
Query results in specified format:
67
- geojson: GeoJSON dictionary
68
- json: JSON dictionary
69
- xml: XML string
70
- csv: List of lists
71
72
Raises:
73
OverpassSyntaxError: Query contains syntax errors
74
TimeoutError: Request timeout occurred
75
MultipleRequestsError: Multiple simultaneous requests attempted
76
ServerLoadError: Server is under load
77
ServerRuntimeError: Server encountered runtime error during query execution
78
UnknownOverpassError: Unknown error occurred
79
"""
80
81
def search(self, feature_type: str, regex: bool = False):
82
"""
83
Search for features (currently not implemented).
84
85
Args:
86
feature_type: Type of feature to search for
87
regex: Whether to use regex matching
88
89
Raises:
90
NotImplementedError: This method is not yet implemented
91
"""
92
```
93
94
#### Usage Examples
95
96
```python
97
# Basic query
98
response = api.get('node["name"="Salt Lake City"]')
99
100
# Different response formats
101
json_response = api.get('node["name"="Springfield"]', responseformat="json")
102
xml_response = api.get('node["name"="Springfield"]', responseformat="xml")
103
104
# CSV format with field specification
105
csv_response = api.get(
106
'node["name"="Springfield"]["place"]',
107
responseformat="csv(name,::lon,::lat)"
108
)
109
110
# Historical query
111
response = api.get(
112
'node["name"="Salt Lake City"]',
113
date="2020-04-28T00:00:00Z"
114
)
115
116
# Raw query (no template building)
117
raw_response = api.get(
118
'[out:json][timeout:25];node["name"="Salt Lake City"];out body;',
119
build=False
120
)
121
```
122
123
### Server Status Monitoring
124
125
Monitor Overpass API server status and available query slots to optimize request timing.
126
127
```python { .api }
128
@property
129
def slots_available(self) -> int:
130
"""
131
Get count of immediately available query slots.
132
133
Returns:
134
Number of available slots (0 means all slots occupied)
135
"""
136
137
@property
138
def slots_waiting(self) -> Tuple[datetime, ...]:
139
"""
140
Get waiting slot availability times.
141
142
Returns:
143
Tuple of datetime objects when waiting slots will become available
144
"""
145
146
@property
147
def slots_running(self) -> Tuple[datetime, ...]:
148
"""
149
Get running slot completion times.
150
151
Returns:
152
Tuple of datetime objects when running slots will be freed
153
"""
154
155
@property
156
def slot_available_datetime(self) -> Optional[datetime]:
157
"""
158
Get next slot availability time.
159
160
Returns:
161
None if slot available now, otherwise datetime when next slot available
162
"""
163
164
@property
165
def slot_available_countdown(self) -> int:
166
"""
167
Get seconds until next slot available.
168
169
Returns:
170
0 if slot available now, otherwise seconds until next slot
171
"""
172
```
173
174
#### Usage Example
175
176
```python
177
# Check server status before querying
178
if api.slots_available > 0:
179
response = api.get(query)
180
else:
181
wait_time = api.slot_available_countdown
182
print(f"Server busy, wait {wait_time} seconds")
183
184
# Monitor server load
185
print(f"Available slots: {api.slots_available}")
186
print(f"Next available at: {api.slot_available_datetime}")
187
```
188
189
### Legacy Method Names
190
191
Deprecated uppercase method names for backward compatibility.
192
193
```python { .api }
194
def Get(self, *args, **kwargs):
195
"""Deprecated: Use get() instead."""
196
197
def Search(self, *args, **kwargs):
198
"""Deprecated: Use search() instead."""
199
```
200
201
## Constants
202
203
```python { .api }
204
SUPPORTED_FORMATS = ["geojson", "json", "xml", "csv"]
205
```
206
207
Available response formats for query results.