0
# Authentication & Configuration
1
2
Complete authentication and configuration options for the osmapi library, supporting multiple authentication methods and server configurations for both production and development environments.
3
4
## Capabilities
5
6
### Basic Authentication
7
8
Simple username/password authentication for OSM API access.
9
10
```python { .api }
11
def __init__(self, username=None, password=None, **kwargs):
12
"""
13
Initialize OsmApi with username/password authentication.
14
15
Parameters:
16
- username (str): OSM username
17
- password (str): OSM password
18
"""
19
```
20
21
**Usage Example:**
22
23
```python
24
import osmapi
25
26
# Direct credentials
27
api = osmapi.OsmApi(username="your_username", password="your_password")
28
29
# Use with production server (default)
30
api = osmapi.OsmApi(
31
username="your_username",
32
password="your_password",
33
api="https://www.openstreetmap.org"
34
)
35
36
# Use with development server
37
api = osmapi.OsmApi(
38
username="dev_username",
39
password="dev_password",
40
api="https://api06.dev.openstreetmap.org"
41
)
42
```
43
44
### Password File Authentication
45
46
Load credentials from a file for improved security.
47
48
```python { .api }
49
def __init__(self, passwordfile=None, **kwargs):
50
"""
51
Initialize OsmApi with credentials from file.
52
53
Parameters:
54
- passwordfile (str): Path to password file
55
56
File format: username:password (first line)
57
Multiple users: one per line with username:password format
58
"""
59
```
60
61
**Usage Example:**
62
63
```python
64
import osmapi
65
66
# Single user file format: "username:password"
67
api = osmapi.OsmApi(passwordfile="/path/to/credentials.txt")
68
69
# Multi-user file format:
70
# user1:pass1
71
# user2:pass2
72
api = osmapi.OsmApi(passwordfile="/path/to/multi_user_creds.txt")
73
```
74
75
### OAuth 2.0 Authentication
76
77
Advanced authentication using OAuth 2.0 with custom session objects.
78
79
```python { .api }
80
def __init__(self, session=None, **kwargs):
81
"""
82
Initialize OsmApi with OAuth 2.0 session.
83
84
Parameters:
85
- session: requests.Session object with OAuth credentials
86
"""
87
```
88
89
**Usage Example:**
90
91
```python
92
import osmapi
93
from oauthcli import OpenStreetMapAuth # External OAuth library
94
95
# OAuth 2.0 setup
96
client_id = "your_client_id"
97
client_secret = "your_client_secret"
98
auth = OpenStreetMapAuth(client_id, client_secret, ["write_api"]).auth_code()
99
100
# Use OAuth session
101
api = osmapi.OsmApi(session=auth.session)
102
103
# OAuth with development server
104
api = osmapi.OsmApi(
105
session=auth.session,
106
api="https://api06.dev.openstreetmap.org"
107
)
108
```
109
110
### Server Configuration
111
112
Configure API endpoint and application identification.
113
114
```python { .api }
115
def __init__(
116
self,
117
api="https://www.openstreetmap.org",
118
appid="",
119
created_by="osmapi/4.3.0",
120
timeout=30,
121
**kwargs
122
):
123
"""
124
Initialize OsmApi with server configuration.
125
126
Parameters:
127
- api (str): API base URL
128
- appid (str): Application identifier
129
- created_by (str): User agent string
130
- timeout (int): Request timeout in seconds
131
"""
132
```
133
134
**Usage Example:**
135
136
```python
137
import osmapi
138
139
# Production server (default)
140
api = osmapi.OsmApi()
141
142
# Development server
143
api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org")
144
145
# Custom application identification
146
api = osmapi.OsmApi(
147
appid="MyGISApp/1.0",
148
created_by="MyGISApp/1.0 (osmapi/4.3.0)"
149
)
150
151
# Custom timeout
152
api = osmapi.OsmApi(timeout=60) # 60 seconds
153
```
154
155
### Automatic Changeset Configuration
156
157
Configure automatic changeset management for streamlined editing workflows.
158
159
```python { .api }
160
def __init__(
161
self,
162
changesetauto=False,
163
changesetautotags={},
164
changesetautosize=500,
165
changesetautomulti=1,
166
**kwargs
167
):
168
"""
169
Initialize OsmApi with automatic changeset configuration.
170
171
Parameters:
172
- changesetauto (bool): Enable automatic changeset management
173
- changesetautotags (dict): Default tags for auto-created changesets
174
- changesetautosize (int): Maximum elements per changeset
175
- changesetautomulti (int): Number of uploads before closing changeset
176
"""
177
```
178
179
**Usage Example:**
180
181
```python
182
import osmapi
183
184
# Enable automatic changeset management
185
api = osmapi.OsmApi(
186
username="your_username",
187
password="your_password",
188
changesetauto=True,
189
changesetautotags={
190
"comment": "Automated data import",
191
"source": "Survey GPS data",
192
"created_by": "MyApp/1.0"
193
},
194
changesetautosize=100, # 100 elements per upload
195
changesetautomulti=5 # 5 uploads per changeset
196
)
197
198
# Operations will automatically manage changesets
199
api.NodeCreate({"lat": 47.6, "lon": -122.3, "tag": {"name": "Test"}})
200
api.NodeCreate({"lat": 47.61, "lon": -122.31, "tag": {"name": "Test2"}})
201
# ... more operations handled automatically
202
```
203
204
### Session Management
205
206
Advanced session configuration with custom HTTP sessions.
207
208
```python { .api }
209
def __init__(self, session=None, **kwargs):
210
"""
211
Initialize OsmApi with custom session configuration.
212
213
Parameters:
214
- session: Custom requests.Session object
215
"""
216
217
def close(self):
218
"""Close HTTP session and clean up resources."""
219
220
def __enter__(self):
221
"""Context manager entry."""
222
223
def __exit__(self, *args):
224
"""Context manager exit with cleanup."""
225
```
226
227
**Usage Example:**
228
229
```python
230
import osmapi
231
import requests
232
233
# Custom session with specific configuration
234
session = requests.Session()
235
session.headers.update({"X-Custom-Header": "MyValue"})
236
session.proxies = {"https": "https://proxy.example.com:8080"}
237
238
api = osmapi.OsmApi(session=session)
239
240
# Context manager usage
241
with osmapi.OsmApi(username="user", password="pass") as api:
242
node = api.NodeGet(123)
243
# Session automatically closed on exit
244
```
245
246
### Server Capabilities
247
248
Query API server capabilities and limitations.
249
250
```python { .api }
251
def Capabilities(self):
252
"""
253
Returns the API capabilities as a dict.
254
255
Returns:
256
dict: Server capabilities including area limits, changeset limits,
257
version info, timeout settings, and status information
258
"""
259
```
260
261
**Usage Example:**
262
263
```python
264
import osmapi
265
266
api = osmapi.OsmApi()
267
caps = api.Capabilities()
268
269
print(f"API version: {caps['version']['minimum']}-{caps['version']['maximum']}")
270
print(f"Max area: {caps['area']['maximum']} square degrees")
271
print(f"Max changeset elements: {caps['changesets']['maximum_elements']}")
272
print(f"API status: {caps['status']['api']}")
273
print(f"Database status: {caps['status']['database']}")
274
```
275
276
## Configuration Validation
277
278
The library automatically validates configuration and raises appropriate errors:
279
280
- **Production Server Protection**: Prevents test changesets on production server
281
- **Authentication Validation**: Ensures credentials are provided for write operations
282
- **Parameter Validation**: Validates configuration parameters and combinations
283
- **Server Connectivity**: Tests connection and API compatibility
284
285
## Environment-Specific Setup
286
287
### Development Environment
288
289
```python
290
import osmapi
291
292
# Development server setup
293
api = osmapi.OsmApi(
294
username="dev_username",
295
password="dev_password",
296
api="https://api06.dev.openstreetmap.org",
297
appid="MyApp-Dev/1.0"
298
)
299
```
300
301
### Production Environment
302
303
```python
304
import osmapi
305
import os
306
307
# Production with environment variables
308
api = osmapi.OsmApi(
309
username=os.getenv("OSM_USERNAME"),
310
password=os.getenv("OSM_PASSWORD"),
311
api="https://www.openstreetmap.org",
312
appid="MyApp/1.0",
313
changesetautotags={
314
"comment": "Automated maintenance",
315
"source": "Official government data"
316
}
317
)
318
```
319
320
### Secure Credential Management
321
322
```python
323
import osmapi
324
from pathlib import Path
325
326
# Secure password file approach
327
credentials_file = Path.home() / ".osm" / "credentials"
328
api = osmapi.OsmApi(
329
passwordfile=str(credentials_file),
330
api="https://www.openstreetmap.org"
331
)
332
```