Python · API · Intermediate

Orders

5 tasks

Place orders from your cart and inspect your order history.

Order flow and endpoints

#
An order represents a purchase — it captures the cart contents at a point in time. Once placed, the cart is cleared automatically and the order becomes available in your order history. The order flow has two stages: 1. Fill the cart — add products using POST /api/cart/items/ (covered in the cart topic). 2. Place the order — POST to /api/orders/ with your phone number in the body. Order endpoints: ``` POST /api/orders/ Place an order from the current cart GET /api/orders/ List all your past orders GET /api/orders/{id}/ Get details of one order ``` All order endpoints require authentication. A placed order looks like this: ```json { "id": 5, "created_timestamp": "2025-06-23T10:15:00Z", "phone_number": "+1234567890", "status": "Processing", "items": [ {"id": 5, "name": "Oak Chair", "price": "149.99", "quantity": 2} ] } ``` Note that items are flat — each item has name, price, and quantity directly, not nested under a product key. The price field records the price at the time of purchase.

Placing and retrieving orders

#
Full flow — register, add items, place an order, check history: ```python import requests BASE_URL = 'https://apilearn.tukas.dev' # Authenticate token = requests.post(f'{BASE_URL}/api/auth/token/', json={ 'username': 'alice42', 'password': 'securepass123', }).json()['token'] session = requests.Session() session.headers['Authorization'] = f'Token {token}' # Add two products to cart products = session.get(f'{BASE_URL}/api/products/').json()['results'] for product in products[:2]: session.post(f'{BASE_URL}/api/cart/items/', json={ 'product_slug': product['slug'], 'quantity': 1, }) # Place the order — phone_number is required response = session.post(f'{BASE_URL}/api/orders/', json={'phone_number': '+1234567890'}) print(response.status_code) # 201 Created order = response.json() print('Order id:', order['id']) print('Status:', order['status']) print('Items:', len(order['items'])) ``` List all your orders: ```python orders = session.get(f'{BASE_URL}/api/orders/').json() print(f'You have {orders["count"]} orders') for o in orders['results']: print(f" Order #{o['id']} — {o['status']}") ``` The order list is paginated, just like products. Each item in results has id, status, created_timestamp, and items. Get detailed info on a specific order: ```python order_id = orders['results'][0]['id'] detail = session.get(f'{BASE_URL}/api/orders/{order_id}/').json() for item in detail['items']: print(f" {item['name']} x{item['quantity']} @ {item['price']}") ``` If you try to POST /api/orders/ with an empty cart, you get a 400 error — there is nothing to order. Always check that your cart has items first.

Order endpoints reference

#
Order endpoints (all require auth): ``` POST /api/orders/ Place an order from current cart body: {phone_number: str} returns: 201 + order object error: 400 if cart is empty GET /api/orders/ List all orders (paginated) returns: {count, next, previous, results: [...]} GET /api/orders/{id}/ Order detail returns: full order object with items ``` Order object fields: ``` id int Order id created_timestamp string ISO 8601 timestamp phone_number string Phone number provided at checkout status string e.g. "Processing" items list List of order item objects ``` Order item object: ``` id int Item id name string Product name at time of purchase price string Price at time of purchase quantity int Quantity ordered ```
01

Place an order

#

Add at least one product to your cart, then POST to /api/orders/ to place an order. Print the order id and status from the response.

import requests

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

# 1. Authenticate
# 2. Add a product to cart
# 3. POST /api/orders/ and print order id + total
Solution
import requests

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

token = requests.post(f'{BASE_URL}/api/auth/token/', json={
    'username': 'YOUR_USERNAME', 'password': 'YOUR_PASSWORD',
}).json()['token']

headers = {'Authorization': f'Token {token}'}

product_slug = requests.get(f'{BASE_URL}/api/products/').json()['results'][0]['slug']
requests.post(
    f'{BASE_URL}/api/cart/items/',
    json={'product_slug': product_slug, 'quantity': 1},
    headers=headers,
)

order = requests.post(
    f'{BASE_URL}/api/orders/',
    json={'phone_number': '+1234567890'},
    headers=headers,
).json()
print(order['id'])
print(order['status'])
02

List your orders

#

Fetch the order history from GET /api/orders/. Print how many orders you have and the id and status of each.

import requests

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

# GET /api/orders/ and print count + each order total
Solution
import requests

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

token = requests.post(f'{BASE_URL}/api/auth/token/', json={
    'username': 'YOUR_USERNAME', 'password': 'YOUR_PASSWORD',
}).json()['token']

headers = {'Authorization': f'Token {token}'}
data = requests.get(f'{BASE_URL}/api/orders/', headers=headers).json()
print(f'{data["count"]} orders')
for order in data['results']:
    print(f"  #{order['id']} — {order['status']}")
03

Get order details

#

Place an order, then fetch its details from GET /api/orders/{id}/. Print each item name, quantity, and price.

import requests

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

# 1. Authenticate, add items, place order
# 2. GET /api/orders/{id}/ and print each item
Solution
import requests

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

token = requests.post(f'{BASE_URL}/api/auth/token/', json={
    'username': 'YOUR_USERNAME', 'password': 'YOUR_PASSWORD',
}).json()['token']

headers = {'Authorization': f'Token {token}'}

products = requests.get(f'{BASE_URL}/api/products/').json()['results']
for p in products[:2]:
    requests.post(
        f'{BASE_URL}/api/cart/items/',
        json={'product_slug': p['slug'], 'quantity': 1},
        headers=headers,
    )

order = requests.post(
    f'{BASE_URL}/api/orders/',
    json={'phone_number': '+1234567890'},
    headers=headers,
).json()
order_id = order['id']

detail = requests.get(f'{BASE_URL}/api/orders/{order_id}/', headers=headers).json()
for item in detail['items']:
    print(item['name'], item['quantity'], item['price'])
04

Full order flow

#

Complete the full flow in one script: authenticate, add 3 products to the cart, place an order, confirm the order appears in the order list, and print the order id and item count.

import requests

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

# Full flow: auth → add 3 items → place order → confirm in list
Solution
import requests

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

token = requests.post(f'{BASE_URL}/api/auth/token/', json={
    'username': 'YOUR_USERNAME', 'password': 'YOUR_PASSWORD',
}).json()['token']

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

products = session.get(f'{BASE_URL}/api/products/').json()['results'][:3]
for p in products:
    session.post(f'{BASE_URL}/api/cart/items/', json={'product_slug': p['slug'], 'quantity': 1})

order = session.post(f'{BASE_URL}/api/orders/', json={'phone_number': '+1234567890'}).json()
order_id = order['id']

orders_list = session.get(f'{BASE_URL}/api/orders/').json()
order_ids = [o['id'] for o in orders_list['results']]
print(f'Order {order_id} in list: {order_id in order_ids}')
print(f'Items: {len(order["items"])}')
05

Calculate total spend

#

Place two separate orders (add items, place, add more items, place again). Then fetch all orders and calculate your total spend across all orders. Print the sum.

import requests

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

# Place 2 orders, then sum all order totals
Solution
import requests

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

token = requests.post(f'{BASE_URL}/api/auth/token/', json={
    'username': 'YOUR_USERNAME', 'password': 'YOUR_PASSWORD',
}).json()['token']

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

products = session.get(f'{BASE_URL}/api/products/').json()['results']

# First order
session.post(f'{BASE_URL}/api/cart/items/', json={'product_slug': products[0]['slug'], 'quantity': 1})
session.post(f'{BASE_URL}/api/orders/', json={'phone_number': '+1234567890'})

# Second order
session.post(f'{BASE_URL}/api/cart/items/', json={'product_slug': products[1]['slug'], 'quantity': 2})
session.post(f'{BASE_URL}/api/orders/', json={'phone_number': '+1234567890'})

orders = session.get(f'{BASE_URL}/api/orders/').json()['results']
total_spend = sum(
    float(item['price']) * item['quantity']
    for o in orders
    for item in o['items']
)
print(f'Total spend: {total_spend:.2f}')