Skip to content

Instantly share code, notes, and snippets.

@JorgeMartinezG
Created August 24, 2021 16:13
Show Gist options
  • Save JorgeMartinezG/82c8a1cecadea1888b2639474946b4fd to your computer and use it in GitHub Desktop.
Save JorgeMartinezG/82c8a1cecadea1888b2639474946b4fd to your computer and use it in GitHub Desktop.
import requests
from urllib.parse import parse_qs
from string import ascii_letters
from random import choice
client_id = ""
client_secret = ""
redirect_uri = "http://127.0.0.1/callback"
auth_url = "https://www.openstreetmap.org/oauth2/authorize"
token_url = "https://www.openstreetmap.org/oauth2/token"
api_url = "https://www.openstreetmap.org/api/0.6/user/details.json"
scope = ["read_prefs", "write_api"] # Validate when creating your client.
state = "".join([choice(ascii_letters) for i in range(15)])
params = {
"client_id": client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"scope": "+".join(scope),
"state": state,
}
# Transform to url query string.
params_str = "&".join([f"{k}={v}" for k, v in params.items()])
print(f"{auth_url}?{params_str}")
# Second endpoint. //TODO on callback url.
authorization_response = input("Paste the full redirected URL here: ")
query_params = parse_qs(authorization_response.split("?")[1])
query_params = {k: v[0] for k, v in query_params.items()}
data = {
"grant_type": "authorization_code",
"code": query_params["code"],
"redirect_uri": redirect_uri,
"state": query_params["state"],
}
token_data = requests.post(
token_url,
data=data,
verify=False,
allow_redirects=False,
auth=(client_id, client_secret),
).json()
headers = {"Authorization": f'Bearer {token_data.get("access_token")}'}
user_data = requests.get(api_url, headers=headers, verify=False).json().get("user")
print(user_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment