Python · API · Intermediate

Shopping Cart

5 tasks

Add, update, and remove cart items using authenticated requests.

Cart API overview

#
The cart API manages a shopping basket tied to your user account. Every request to a cart endpoint requires authentication — send the Authorization header just like you did with the profile endpoints. The cart has two endpoint groups: Cart overview: ``` GET /api/cart/ View your cart (total, items list) ``` Cart items: ``` POST /api/cart/items/ Add a product to the cart PATCH /api/cart/items/{id}/ Update quantity of one item DELETE /api/cart/items/{id}/ Remove one item DELETE /api/cart/items/ Clear the entire cart ``` The GET /api/cart/ response looks like this: ```json { "items": [ { "id": 42, "product": {"id": 7, "name": "Oak Chair", "price": "149.99", ...}, "quantity": 1, "products_price": "149.99" } ], "total_price": "149.99", "total_quantity": 1 } ``` Each item in the cart has its own id (the cart item id, not the product id). You need the cart item id to update or delete that specific item. To add a product to the cart, you need its slug — get it from the `slug` field in the /api/products/ response.

Adding, updating, and removing cart items

#
Full cart workflow — from empty to modified to cleared: ```python import requests BASE_URL = 'https://apilearn.tukas.dev' # Authenticate first 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}' # View empty cart cart = session.get(f'{BASE_URL}/api/cart/').json() print('Items in cart:', len(cart['items'])) ``` Add a product (you need the product slug from /api/products/): ```python # Fetch a product to get its slug product = session.get(f'{BASE_URL}/api/products/1/').json() product_slug = product['slug'] # Add it with quantity=2 response = session.post(f'{BASE_URL}/api/cart/items/', json={ 'product_slug': product_slug, 'quantity': 2, }) print(response.status_code) # 201 Created item = response.json() cart_item_id = item['id'] # save this — needed to update/delete print('Cart item id:', cart_item_id) ``` Update the quantity: ```python response = session.patch( f'{BASE_URL}/api/cart/items/{cart_item_id}/', json={'quantity': 5}, ) print(response.json()['quantity']) # 5 ``` Remove that item: ```python response = session.delete(f'{BASE_URL}/api/cart/items/{cart_item_id}/') print(response.status_code) # 204 No Content ``` Clear the entire cart at once: ```python response = session.delete(f'{BASE_URL}/api/cart/items/') print(response.status_code) # 204 No Content # Verify it's empty cart = session.get(f'{BASE_URL}/api/cart/').json() print('Items after clear:', len(cart['items'])) # 0 ``` Note the difference between the two DELETE endpoints: /api/cart/items/{id}/ removes a single item, /api/cart/items/ (without an id) removes all items.

Cart API reference

#
Cart endpoints (all require auth): ``` GET /api/cart/ View cart with items and total POST /api/cart/items/ Add item body: {product_slug: str, quantity: int} returns: 201 + cart item object PATCH /api/cart/items/{id}/ Update quantity body: {quantity: int} returns: 200 + updated item DELETE /api/cart/items/{id}/ Remove one item → 204 DELETE /api/cart/items/ Clear all items → 204 ``` Cart response shape: ```json {"items": [...], "total_price": "149.99", "total_quantity": 1} ``` Cart item object: ```json {"id": 42, "product": {...}, "quantity": 2, "products_price": "299.98"} ``` Key distinction: ``` product.slug — the product's slug, use when adding to cart item.id — the cart item's id, use when patching/deleting ```
01

View your cart

#

Authenticate and send a GET to /api/cart/. Print the number of items in the cart and the total price.

import requests

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

# 1. Get a token
# 2. GET /api/cart/ and print item count and 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}'}
cart = requests.get(f'{BASE_URL}/api/cart/', headers=headers).json()
print(len(cart['items']))
print(cart['total_price'])
02

Add a product to cart

#

Find any product from /api/products/ and add it to your cart with quantity=1. Print the cart item id from the response.

import requests

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

# 1. Authenticate
# 2. Pick a product id from /api/products/
# 3. POST to /api/cart/items/ and print the cart item id
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}'}

# Pick first product — take its slug
product_slug = requests.get(f'{BASE_URL}/api/products/').json()['results'][0]['slug']

response = requests.post(
    f'{BASE_URL}/api/cart/items/',
    json={'product_slug': product_slug, 'quantity': 1},
    headers=headers,
)
print(response.json()['id'])
03

Update item quantity

#

Add a product to your cart, then update its quantity to 3 using PATCH /api/cart/items/{id}/. Print the updated quantity from the response.

import requests

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

# 1. Authenticate
# 2. Add a product
# 3. PATCH the quantity to 3
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']
item = requests.post(
    f'{BASE_URL}/api/cart/items/',
    json={'product_slug': product_slug, 'quantity': 1},
    headers=headers,
).json()

cart_item_id = item['id']
updated = requests.patch(
    f'{BASE_URL}/api/cart/items/{cart_item_id}/',
    json={'quantity': 3},
    headers=headers,
).json()
print(updated['quantity'])
04

Remove one item

#

Add a product to your cart, then remove it with DELETE /api/cart/items/{id}/. Verify the cart is empty by fetching it again and printing the item count.

import requests

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

# 1. Authenticate
# 2. Add a product
# 3. Delete that item
# 4. Verify cart is empty
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']
item = requests.post(
    f'{BASE_URL}/api/cart/items/',
    json={'product_slug': product_slug, 'quantity': 1},
    headers=headers,
).json()

requests.delete(f'{BASE_URL}/api/cart/items/{item["id"]}/', headers=headers)

cart = requests.get(f'{BASE_URL}/api/cart/', headers=headers).json()
print(len(cart['items']))
05

Add two products and clear the cart

#

Add two different products to your cart. Print the total. Then clear the cart with DELETE /api/cart/items/ and verify it is empty.

import requests

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

# 1. Authenticate
# 2. Add two different products
# 3. Print total
# 4. Clear cart
# 5. Confirm cart is empty
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']
product_slugs = [products[0]['slug'], products[1]['slug']]

for slug in product_slugs:
    requests.post(
        f'{BASE_URL}/api/cart/items/',
        json={'product_slug': slug, 'quantity': 1},
        headers=headers,
    )

cart = requests.get(f'{BASE_URL}/api/cart/', headers=headers).json()
print('total:', cart['total_price'])

requests.delete(f'{BASE_URL}/api/cart/items/', headers=headers)

cart = requests.get(f'{BASE_URL}/api/cart/', headers=headers).json()
print('items after clear:', len(cart['items']))