FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
It is created on top of Starlette. A FastAPI app is basically a Starlette app, that is why you can just use Authlib Starlette integration to create OAuth clients for FastAPI.
Create OAuth client
A typical OAuth client for Starlette or FastAPI:
from authlib.integrations.starlette_client import OAuth
from starlette.config import Config
config = Config('.env') # read config from .env file
oauth = OAuth(config)
We will create a twitter login example for FastAPI. Like all web frameworks integrations in Authlib, we need to register a remote:
oauth.register(
name='twitter',
api_base_url='https://api.twitter.com/1.1/',
request_token_url='https://api.twitter.com/oauth/request_token',
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authenticate',
)
We don't need to add client_id
and client_secret
here, because they are in .env
file. You are not supposed to hard code them in the code in real products.
Implement login route
First, create a FastAPI application:
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="secret-string")
We need this SessionMiddleware
, because Authlib will use request.session
to store temporary codes and states.
Next, the /login
route will redirect us to Twitter website to grant access:
@app.route('/login')
async def login(request: Request):
# absolute url for callback
# we will define it below
redirect_uri = request.url_for('auth')
return await oauth.twitter.authorize_redirect(request, redirect_uri)
The above code will exchange request_token
and redirect to Twitter website for you.
Handle authentication callback
When you grant access from Twitter website, twitter will redirect back to your given redirect_uri
, which is request.url_for('auth')
:
@app.route('/auth')
async def auth(request: Request):
token = await oauth.twitter.authorize_access_token(request)
url = 'account/verify_credentials.json'
resp = await oauth.twitter.get(
url, params={'skip_status': True}, token=token)
user = resp.json()
return user
The above code will exchange an access_token
. You can use the token
to access users' resources. In the above example, we are requesting the authenticated user's profile information.
Hint
You can register a Twitter OAuth Client at https://developer.twitter.com/en/apps. Remember to add the full auth
url in Callback URL.
You can check the full example: https://github.com/authlib/demo-oauth-client/tree/master/fastapi-twitter-login.