Python · API · Intermediate

Token Authentication

5 tasks

Register a user, obtain an auth token, and make authenticated API requests.

Token authentication flow

#
Some API endpoints require authentication — you must prove who you are before the server will respond with data. The most common lightweight scheme is token auth. The flow has three steps: 1. Register — create a user account by POSTing a username and password. 2. Get a token — exchange your credentials for a token string. 3. Send the token — include it in the Authorization header of every authenticated request. Without the header, the server returns 401 Unauthorized. With it, the server knows who you are and what you are allowed to do. The header format for token auth is: ``` Authorization: Token <your-token-string> ``` In requests: ```python import requests BASE_URL = 'https://apilearn.tukas.dev' token = 'abc123...' headers = {'Authorization': f'Token {token}'} response = requests.get(f'{BASE_URL}/api/users/profile/', headers=headers) ``` The token identifies you — it is a secret, just like a password. Never print it to shared output or commit it to version control. In scripts, store it in a variable and pass it through headers. Important: on apilearn.tukas.dev the database resets daily at midnight UTC. Users and tokens created today will not exist tomorrow. Always register and get a fresh token at the start of a session.

Registration, token, and authenticated requests

#
Step 1 — register a new user: ```python import requests BASE_URL = 'https://apilearn.tukas.dev' register_data = { 'username': 'alice42', 'password': 'securepass123', 'email': '[email protected]', # optional } response = requests.post(f'{BASE_URL}/api/users/register/', json=register_data) print(response.status_code) # 201 Created print(response.json()) # The 201 response also contains a 'token' field — you can use it directly # and skip the separate /api/auth/token/ call if you just registered. ``` Step 2 — get a token with those credentials: ```python token_data = {'username': 'alice42', 'password': 'securepass123'} response = requests.post(f'{BASE_URL}/api/auth/token/', json=token_data) token = response.json()['token'] print(token) # long alphanumeric string ``` Step 3 — use the token to access protected endpoints: ```python headers = {'Authorization': f'Token {token}'} # View profile profile = requests.get(f'{BASE_URL}/api/users/profile/', headers=headers).json() print(profile['username']) # 'alice42' # View cart cart = requests.get(f'{BASE_URL}/api/cart/', headers=headers).json() print(cart) ``` Using requests.Session() lets you set the header once and reuse it across all requests: ```python session = requests.Session() session.headers['Authorization'] = f'Token {token}' # No headers= needed on individual calls profile = session.get(f'{BASE_URL}/api/users/profile/').json() cart = session.get(f'{BASE_URL}/api/cart/').json() print(profile['username']) print(cart) ``` Session is particularly useful when you need to make many authenticated calls in sequence — you define the header once and forget about it.

Token auth reference

#
Auth endpoints: ``` POST /api/users/register/ Create a new user body: {username, password, email (optional)} success: 201, returns user object + token field POST /api/auth/token/ Get token for existing user body: {username, password} success: 200, returns {token: '...'} DELETE /api/auth/token/ Revoke current token (requires auth) ``` Protected endpoints (require Authorization header): ``` GET/PUT/PATCH /api/users/profile/ GET /api/cart/ POST /api/cart/items/ GET /api/orders/ POST /api/orders/ ``` Authorization header: ``` Authorization: Token <token-string> ``` Per-request pattern: ```python headers = {'Authorization': f'Token {token}'} requests.get(url, headers=headers) ``` Session pattern: ```python session = requests.Session() session.headers['Authorization'] = f'Token {token}' session.get(url1) session.get(url2) ```
01

Register a new user

#

Register a new user by sending a POST to /api/users/register/ with a username and password. Print the status code and the response JSON.

import requests

BASE_URL = 'https://apilearn.tukas.dev'

data = {
    'username': 'testuser01',
    'password': 'mypassword123',
}

# Register and print status code + response
Solution
import requests

BASE_URL = 'https://apilearn.tukas.dev'

data = {
    'username': 'testuser01',
    'password': 'mypassword123',
}
response = requests.post(f'{BASE_URL}/api/users/register/', json=data)
print(response.status_code)
print(response.json())
02

Get an auth token

#

POST to /api/auth/token/ with your username and password and print the token string from the response.

import requests

BASE_URL = 'https://apilearn.tukas.dev'

credentials = {
    'username': 'testuser01',
    'password': 'mypassword123',
}

# Get token and print it
Solution
import requests

BASE_URL = 'https://apilearn.tukas.dev'

credentials = {
    'username': 'testuser01',
    'password': 'mypassword123',
}
response = requests.post(f'{BASE_URL}/api/auth/token/', json=credentials)
token = response.json()['token']
print(token)
03

Access a protected endpoint

#

Using the token you obtained, send a GET to /api/users/profile/ with the Authorization header set. Print the username from the profile response.

import requests

BASE_URL = 'https://apilearn.tukas.dev'

token = 'PASTE_YOUR_TOKEN_HERE'

# GET profile with Authorization header and print username
Solution
import requests

BASE_URL = 'https://apilearn.tukas.dev'

token = 'PASTE_YOUR_TOKEN_HERE'

headers = {'Authorization': f'Token {token}'}
response = requests.get(f'{BASE_URL}/api/users/profile/', headers=headers)
print(response.json()['username'])
04

See what happens without auth

#

Try to GET /api/cart/ without any Authorization header. Print the status code and the error message from the response.

import requests

BASE_URL = 'https://apilearn.tukas.dev'

# GET /api/cart/ with no auth header
Solution
import requests

BASE_URL = 'https://apilearn.tukas.dev'

response = requests.get(f'{BASE_URL}/api/cart/')
print(response.status_code)
print(response.json())
05

Use a Session for multiple calls

#

Register a user, get a token, then use requests.Session() to make two authenticated calls — GET /api/users/profile/ and GET /api/cart/ — without specifying the Authorization header on each call. Print the username from the profile and the cart response.

import requests

BASE_URL = 'https://apilearn.tukas.dev'

# 1. Register
# 2. Get token
# 3. Create session with auth header
# 4. Make two calls using the session
Solution
import requests

BASE_URL = 'https://apilearn.tukas.dev'

# Register
reg = requests.post(f'{BASE_URL}/api/users/register/', json={
    'username': 'sessionuser01', 'password': 'securepass123',
})

# Get token
token = requests.post(f'{BASE_URL}/api/auth/token/', json={
    'username': 'sessionuser01', 'password': 'securepass123',
}).json()['token']

# Session
session = requests.Session()
session.headers['Authorization'] = f'Token {token}'

profile = session.get(f'{BASE_URL}/api/users/profile/').json()
cart = session.get(f'{BASE_URL}/api/cart/').json()

print(profile['username'])
print(cart)