OAuth part II – Setting up API Access credentials with Google Cloud

If you’ve followed part 1 you’ll have a GCP project and enabled the Search Console API.

From here you’ll need to configure a few things to make calls to the API, in your project head to APIs & Services -> credentials (https://console.cloud.google.com/apis/credentials)

In the create credentials menu choose OAuth Client ID and then Web Application in the Application Type dropdown

You’ll then need to fill in some additional details including a Name and Redirect URI. When you generate an OAuth link for a user to grant access to a service, the API needs to know where to point the browser back to once the OAuth process has completed.
In FastAPI this is http://localhost:9000/ then the endpoint you’ve set up to handle the api sending data back to, I’ve called it oath_callback.
In FastAPI this needs to be a GET method, so in your router create a get method – if you don’t want it to appear in the swagger docs you can exclude it from the schema.

# Callback for Google Auth to save data to database
@router.get("/oauth_callback", response_model=CredentialsGet, include_in_schema=False)
async def create_access_credentials(
    request: Request,
    data_base: Session = Depends(get_db)
    params = request.query_params

    if params.get('error'):
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail="access to the API denied")
    if params.get('code'):
        client = ast.literal_eval(params.get('state'))
        client_id = client.get('auth_client_id')
        return await GoogleAuth(data_base, client_id).save_access_credentials(params.get('code'))

We’re using request to extract the parameters and handling any errors – you can build this out a little more but to get up and running you can just push a response error.

The key parameter we’re looking for is ‘code’ – this a string the API returns which allows you to then get both the access & refresh token for the user, so you can then make subsequent API calls once access has been granted.

We then pass this into the service to make an API call to retrieve the Access & Refresh tokens… and test making API calls – this will come in the next post.