| 1 |
# install oauthlib for requests: pip install requests-oauth2client |
| 2 |
from requests_oauth2client import OAuth2Client, OAuth2AuthorizationCodeAuth |
| 3 |
import requests |
| 4 |
import webbrowser |
| 5 |
import osmapi |
| 6 |
from dotenv import load_dotenv, find_dotenv |
| 7 |
import os |
| 8 |
|
| 9 |
load_dotenv(find_dotenv()) |
| 10 |
|
| 11 |
# Credentials you get from registering a new application |
| 12 |
# register here: https://master.apis.dev.openstreetmap.org/oauth2/applications |
| 13 |
# or on production: https://www.openstreetmap.org/oauth2/applications |
| 14 |
client_id = os.getenv("OSM_OAUTH_CLIENT_ID") |
| 15 |
client_secret = os.getenv("OSM_OAUTH_CLIENT_SECRET") |
| 16 |
|
| 17 |
# special value for redirect_uri for non-web applications |
| 18 |
redirect_uri = "urn:ietf:wg:oauth:2.0:oob" |
| 19 |
|
| 20 |
authorization_base_url = "https://master.apis.dev.openstreetmap.org/oauth2/authorize" |
| 21 |
token_url = "https://master.apis.dev.openstreetmap.org/oauth2/token" |
| 22 |
|
| 23 |
oauth2client = OAuth2Client( |
| 24 |
token_endpoint=token_url, |
| 25 |
authorization_endpoint=authorization_base_url, |
| 26 |
redirect_uri=redirect_uri, |
| 27 |
auth=(client_id, client_secret), |
| 28 |
code_challenge_method=None, |
| 29 |
) |
| 30 |
|
| 31 |
# open OSM website to authrorize user using the write_api and write_notes scope |
| 32 |
scope = ["write_api", "write_notes"] |
| 33 |
az_request = oauth2client.authorization_request(scope=scope) |
| 34 |
print(f"Authorize user using this URL: {az_request.uri}") |
| 35 |
webbrowser.open(az_request.uri) |
| 36 |
|
| 37 |
# create a new requests session using the OAuth authorization |
| 38 |
auth_code = input("Paste the authorization code here: ") |
| 39 |
auth = OAuth2AuthorizationCodeAuth( |
| 40 |
oauth2client, |
| 41 |
auth_code, |
| 42 |
redirect_uri=redirect_uri, |
| 43 |
) |
| 44 |
oauth_session = requests.Session() |
| 45 |
oauth_session.auth = auth |
| 46 |
|
| 47 |
# use the custom session |
| 48 |
|
| 49 |
api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org", session=oauth_session) |
| 50 |
with api.changeset({"comment": "My first test"}) as changeset_id: |
| 51 |
print(f"Part of Changeset {changeset_id}") |
| 52 |
node1 = api.node_create({"lon": 1, "lat": 1, "tag": {}}) |
| 53 |
print(node1) |