python-aiohttpBearer token request example with Python Aiohttp?
This example uses the Aiohttp library to make a request for a bearer token.
import aiohttp
async def get_token():
async with aiohttp.ClientSession() as session:
async with session.post('https://example.com/token',
data={'grant_type': 'client_credentials'},
auth=aiohttp.BasicAuth('client_id', 'client_secret')) as resp:
token = await resp.json()
return token
token = await get_token()
The output of the code will be a JSON object containing the bearer token:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
Code explanation
import aiohttp
- imports the Aiohttp libraryasync def get_token()
- defines an asynchronous function to make the requestasync with session.post('https://example.com/token', data={'grant_type': 'client_credentials'}, auth=aiohttp.BasicAuth('client_id', 'client_secret')) as resp:
- makes a POST request to the token endpoint with the grant type and authentication credentialstoken = await resp.json()
- parses the response as JSONreturn token
- returns the token
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to create a server with Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to close a Python Aiohttp session?
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to close a Python Aiohttp session?
- How to rate limit with Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to download large files with Python Aiohttp?
See more codes...