Python · API · Beginner

Your First Request

5 tasks

Make your first HTTP request with the requests library and read the response.

Making HTTP requests with requests

#
In this section, we'll practice on a special website I created for this purpose. This website is a fake online store that functions exactly like a real one. It has a standard browser user interface and full coverage of all capabilities via the RESTful API. Below, I'll provide several links so you can visit this website and familiarize yourself with it before working on the materials and exercises in this section: The website's main page with information about it: [https://apilearn.tukas.dev/](https://apilearn.tukas.dev/) Specially created detailed documentation for its API (don't worry, you'll start to understand it soon): [https://apilearn.tukas.dev/api/docs/](https://apilearn.tukas.dev/api/docs/) Okay, now that we've briefly explored the website, let's move on to learning how to work with the API. The web runs on a simple conversation: a client sends a request, a server sends a response. When you type a URL in a browser, the browser is the client. With the requests library, your Python script becomes the client. Install it once: ```bash pip install requests ``` To fetch data, use requests.get() with the URL: ```python import requests response = requests.get('https://apilearn.tukas.dev/api/products/') print(response.status_code) # 200 ``` The return value is a Response object. It holds everything the server sent back — a status code, response headers, and a body. Status codes are three-digit numbers that tell you what happened: - 2xx — success. 200 means OK, 201 means a resource was created. - 4xx — client error. You made a bad request (400), forgot auth (401), or requested something that does not exist (404). - 5xx — server error. The server crashed or is overloaded. The .ok attribute gives you a quick boolean check — True for any 2xx status, False for anything else: ```python if response.ok: print('got a valid response') else: print(f'request failed with status {response.status_code}') ``` A common mistake is to call .json() without checking .ok first. If the server returns a 404, .json() will either raise an exception or return an error payload — not the data you wanted. Always check before you read.

Reading the response

#
Once you know the response succeeded, read the body with .json(). It parses the JSON string and returns a Python dict or list: ```python import requests response = requests.get('https://apilearn.tukas.dev/api/products/') data = response.json() print(data['count']) # 372 — total products in the database print(data['next']) # URL to the next page print(len(data['results'])) # items on this page (20 by default) ``` Each item in results is a dict. Access fields with standard key notation: ```python first = data['results'][0] print(first['name']) # 'Tea Table Set with Three Chairs' print(first['price']) # '150.00' print(first['sell_price']) # '135.00' print(first['category']['name']) # 'Kitchen' ``` Prices come back as strings ('150.00'), not floats. This is common in APIs — floating-point arithmetic can introduce tiny errors with money values. Convert with float() or Python's Decimal if you need to do math. Response headers are available through .headers, which works like a case-insensitive dict: ```python print(response.headers['Content-Type']) # application/json print(response.headers.get('X-Request-Id')) # None if the header is not there ``` Use .get() rather than direct indexing when a header might not always be present — otherwise you get a KeyError.

Response object quick reference

#
Response object attributes: ``` .status_code integer The HTTP status code (200, 404, 500, ...) .ok bool True if status_code < 400 .json() dict/list Parse response body as JSON .text str Response body as a decoded string .content bytes Response body as raw bytes .headers dict-like Response headers (case-insensitive keys) .url str Final URL after any redirects ``` Safe JSON reading pattern: ```python response = requests.get(url) if response.ok: data = response.json() else: print(f'Error {response.status_code}: {response.text}') ``` Common status codes: ``` 200 OK Request succeeded, body has data 201 Created Resource was created (after POST) 400 Bad Request Your request has invalid parameters 401 Unauthorized Authentication required 403 Forbidden Authenticated but not allowed 404 Not Found Resource does not exist 500 Internal Server Error Server-side error ```
01

Make your first request

#

Send a GET request to https://apilearn.tukas.dev/api/products/ and print the status code.

import requests

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

# Your code here
Solution
import requests

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

response = requests.get(f'{BASE_URL}/api/products/')
print(response.status_code)
02

Count the products

#

Fetch GET /api/products/ and print the total number of products in the database. The count is in the JSON response, not the length of the results list on this page.

import requests

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

response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()

# Print the total product count
Solution
import requests

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

response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()

print(data['count'])
03

Read the first product

#

Fetch the product list and print the name and sell_price of the first product in the results.

import requests

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

response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()

# Print name and sell_price of the first product
Solution
import requests

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

response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()

first = data['results'][0]
print(first['name'])
print(first['sell_price'])
04

Check for success

#

Make a GET request to https://apilearn.tukas.dev/api/products/. Use response.ok to print 'Success' if the request worked, or 'Failed: {status_code}' if it did not.

import requests

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

response = requests.get(f'{BASE_URL}/api/products/')

# Check response.ok and print the appropriate message
Solution
import requests

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

response = requests.get(f'{BASE_URL}/api/products/')

if response.ok:
    print('Success')
else:
    print(f'Failed: {response.status_code}')
05

Read a response header

#

Fetch the product list and print the value of the Content-Type response header.

import requests

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

response = requests.get(f'{BASE_URL}/api/products/')

# Print the Content-Type header
Solution
import requests

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

response = requests.get(f'{BASE_URL}/api/products/')

print(response.headers['Content-Type'])