Setup

Getting started with Stack in 5 minutes

Welcome to the Python setup guide. If you’re looking for guides for other frameworks, check out the Next.js SDK Setup, React SDK Setup, or the JavaScript SDK Setup.

Our recommended way to use Stack Auth with Python is with the REST API. It provides a fully documented way to interact with Stack Auth from any Python framework, including Flask, FastAPI, and Django.

For the purpose of this guide, we will use the requests library to make HTTP requests to the Stack Auth API. If you haven’t already, you can install it in your environment with pip install requests.

1

Create API keys

First, create an account on the Stack Auth dashboard, and copy your project ID, publishable client key, and secret server key into a safe place (eg. environment variables).

From there, you can access them in your Python code. You can then read them like this:

1import os
2
3stack_project_id = os.getenv("STACK_PROJECT_ID")
4stack_publishable_client_key = os.getenv("STACK_PUBLISHABLE_CLIENT_KEY")
5stack_secret_server_key = os.getenv("STACK_SECRET_SERVER_KEY")
2

Make a request

Next, create a helper function to make requests to the Stack Auth API:

1import requests
2
3def stack_auth_request(method, endpoint, **kwargs):
4 res = requests.request(
5 method,
6 f'https://api.stack-auth.com/{endpoint}',
7 headers={
8 'x-stack-access-type': 'server', # or 'client' if you're only accessing the client API
9 'x-stack-project-id': stack_project_id,
10 'x-stack-publishable-client-key': stack_publishable_client_key,
11 'x-stack-secret-server-key': stack_secret_server_key, # not necessary if access type is 'client'
12 **kwargs.pop('headers', {}),
13 },
14 **kwargs,
15 )
16 if res.status_code >= 400:
17 raise Exception(f"Stack Auth API request failed with {res.status_code}: {res.text}")
18 return res.json()
19
20print(stack_auth_request('GET', '/api/v1/projects/current'))
3

Retrieve the access tokens

If you’re building a backend server, most likely you’ll want to use the currently signed in user’s access token. Most normally, you would send this with all your requests to the backend in an HTTP header.

In Stack Auth’s JavaScript SDK, you can retrieve the access token from the stackClientApp object. Then, you can use said access token to make requests to Stack Auth:

1access_token = # access token retrieved from the JavaScript SDK
2
3print(stack_auth_request('GET', '/api/v1/users/me', headers={
4 'x-stack-access-token': access_token,
5}))
4

Done!

Next steps

Check out the REST API documentation to learn more about the available endpoints and how to use them in your Python application.