Skip to content

Instantly share code, notes, and snippets.

@Zaczero

Zaczero/oauth.py Secret

Last active January 21, 2024 11:29
Show Gist options
  • Save Zaczero/74bdfc57318aef8794f2bbfd2b43a484 to your computer and use it in GitHub Desktop.
Save Zaczero/74bdfc57318aef8794f2bbfd2b43a484 to your computer and use it in GitHub Desktop.
# dependencies: authlib, requests
from authlib.integrations.requests_client import OAuth2Session
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
user_agent = 'YourAppName/0.1'
# api scopes (see https://wiki.openstreetmap.org/wiki/OAuth)
scope = 'read_prefs write_api'
# URI to redirect to after successful authorization
redirect_uri = 'https://example.com/callback'
client = OAuth2Session(
client_id,
client_secret,
scope=scope,
redirect_uri=redirect_uri,
headers={'User-Agent': user_agent})
# generate authorization URL and state (save it for later)
uri, state = client.create_authorization_url('https://www.openstreetmap.org/oauth2/authorize')
# redirect the user to the authorization URL and wait for callback
print(uri)
# ...
# ...
# after authorization, capture the full callback URL
# replace `request.url` with the actual URL you received
callback_url = str(request.url)
# fetch the OAuth2 token using the state and callback URL
client.token = client.fetch_token(
'https://www.openstreetmap.org/oauth2/token',
state=state,
authorization_response=callback_url)
# make authenticated API request
r = client.get('https://api.openstreetmap.org/api/0.6/user/details.json')
r.raise_for_status()
print(r.json())
# dependencies: requests
from requests import Session
pat_token = 'YOUR_PAT_TOKEN'
user_agent = 'YourAppName/0.1'
client = Session(
headers={'User-Agent': user_agent, 'Authorization': f'bearer {pat_token}'})
# make authenticated API request
r = client.get('https://api.openstreetmap.org/api/0.6/user/details.json')
r.raise_for_status()
print(r.json())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment