PYTHON FOR AI • LESSON 5

Requests

Python's Requests library makes it easy to communicate with websites and APIs. In this lesson, you will learn how to send HTTP requests, read responses, send data, use headers, handle parameters, and deal with common errors.

CORE IDEA

Requests lets Python talk to APIs.

Instead of manually building HTTP requests, we can use Python's Requests library. For example, requests.get() sends a GET request and returns a response object containing the server's response.

01

What Is Requests?

Requests is a Python library used to send HTTP requests.

It allows Python programs to communicate with:

  • REST APIs
  • Web servers
  • External applications
  • AI APIs
  • Other services available over HTTP
Python Program
      ↓
Requests Library
      ↓
HTTP Request
      ↓
Server / API
      ↓
HTTP Response
      ↓
Python Program
02

Installing Requests

Requests is not part of Python's standard library, so you normally install it with pip.

pip install requests

If you are using a virtual environment, activate the environment first and then install Requests.

python -m pip install requests
03

Import Requests

After installing the library, import it into your Python program.

import requests

Now Python can use functions provided by the Requests library.

04

Sending a GET Request

The most basic operation is sending a GET request.

A GET request normally means: "Give me some data."

import requests

response = requests.get(
    "https://httpbin.org/get"
)

print(response)

You will get something similar to:

<Response [200]>

The 200 means the request was successful.

05

Understanding the Response Object

requests.get() does not directly return the API data. It returns a Response object.

response = requests.get(
    "https://httpbin.org/get"
)

The response object contains useful information about what the server returned.

Status Code

print(response.status_code)

Example:

200

Response Text

print(response.text)

This returns the response body as text.

Response Headers

print(response.headers)

Headers contain additional information about the response.

06

Reading JSON Responses

Most modern APIs return data in JSON format.

Requests provides the .json() method to convert a JSON response into Python data.

import requests

response = requests.get(
    "https://httpbin.org/json"
)

data = response.json()

print(data)

After calling response.json(), you can work with the result like normal Python data.

print(type(data))

The result will normally be a Python dictionary or list, depending on what the API returns.

07

Query Parameters

Sometimes an API needs additional information in the URL.

For example:

https://example.com/products?category=shoes

The part after ? is a query parameter.

Requests lets us provide query parameters using params.

import requests

params = {
    "category": "shoes"
}

response = requests.get(
    "https://example.com/products",
    params=params
)

Requests builds the query string for you.

Python Dictionary
       ↓
params
       ↓
Query String
       ↓
API URL
08

Sending Data With POST

GET is normally used to retrieve data.

POST is commonly used when we want to send data to a server.

import requests

data = {
    "name": "John",
    "age": 25
}

response = requests.post(
    "https://httpbin.org/post",
    json=data
)

print(response.status_code)
print(response.json())

The json=data argument tells Requests to send the Python dictionary as JSON.

Python Dictionary
       ↓
JSON
       ↓
POST Request
       ↓
Server
       ↓
Response
09

HTTP Headers

Headers allow us to send additional information with an HTTP request.

For example, an API may require an authorization token.

import requests

headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

response = requests.get(
    "https://api.example.com/users",
    headers=headers
)

print(response.status_code)

The server can read these headers and use them when processing the request.

Never hard-code real API secrets into source code that may be committed to Git.

10

Request Timeout

Network requests can take too long or become stuck. Your application should not wait forever.

Use the timeout parameter.

import requests

response = requests.get(
    "https://httpbin.org/get",
    timeout=10
)

print(response.status_code)

Here Python will wait up to 10 seconds for the request before raising a timeout-related exception.

11

Handling Errors

A request can fail for many reasons:

  • Internet connection problems
  • Invalid URL
  • Server unavailable
  • Timeout
  • Authentication failure
  • Rate limiting

Requests provides exceptions that can be handled with try and except.

import requests

try:

    response = requests.get(
        "https://httpbin.org/get",
        timeout=10
    )

    response.raise_for_status()

    data = response.json()

    print(data)

except requests.exceptions.RequestException as error:

    print("Request failed:")
    print(error)

The important method here is:

response.raise_for_status()

It raises an exception when the HTTP response represents an unsuccessful request.

12

PUT, PATCH and DELETE

Requests supports the other common HTTP methods too.

PUT

response = requests.put(
    "https://api.example.com/users/10",
    json={
        "name": "John"
    }
)

PATCH

response = requests.patch(
    "https://api.example.com/users/10",
    json={
        "name": "John"
    }
)

DELETE

response = requests.delete(
    "https://api.example.com/users/10"
)

The exact behavior of PUT and PATCH depends on the API design, but the basic idea is to update an existing resource.

13

Complete API Request Example

Now combine the most important concepts into one example.

import requests


url = "https://httpbin.org/get"

params = {
    "name": "John",
    "age": 25
}

headers = {
    "Accept": "application/json"
}


try:

    response = requests.get(
        url,
        params=params,
        headers=headers,
        timeout=10
    )

    response.raise_for_status()

    data = response.json()

    print("Status:")
    print(response.status_code)

    print("\nData:")
    print(data)


except requests.exceptions.RequestException as error:

    print("API request failed:")
    print(error)

The flow is:

URL
 ↓
Parameters
 ↓
Headers
 ↓
GET Request
 ↓
Server
 ↓
Response
 ↓
Check Status
 ↓
Convert JSON
 ↓
Python Data
14

Why Requests Matters for AI

This library becomes especially useful when building AI applications.

Many AI services expose APIs. Your Python application sends a request and receives the model's response.

Python AI Application
        ↓
Requests
        ↓
HTTP Request
        ↓
AI API
        ↓
LLM
        ↓
JSON Response
        ↓
Python Application

For example, the general structure of an AI API call looks like this:

import requests

response = requests.post(
    "https://api.example.com/chat",
    headers={
        "Authorization": "Bearer API_KEY"
    },
    json={
        "message": "Explain Python"
    },
    timeout=30
)

response.raise_for_status()

data = response.json()

print(data)

The exact URL, headers, request body, and response structure depend on the AI provider. The HTTP and Requests concepts remain the same.

15

Practice Example

Try creating a function that receives a URL and returns the JSON response.

import requests


def get_data(url):

    response = requests.get(
        url,
        timeout=10
    )

    response.raise_for_status()

    return response.json()


data = get_data(
    "https://httpbin.org/json"
)

print(data)

This is an important step because you are moving from writing one-off requests to creating reusable Python code.

16

What You Learned

  • What the Requests library does
  • How to install Requests
  • How to import Requests
  • How to send GET requests
  • How to send POST requests
  • How to send PUT, PATCH and DELETE requests
  • How to read response data
  • How to read JSON responses
  • How to send query parameters
  • How to send HTTP headers
  • Why timeouts are important
  • How to handle request errors
  • How Requests will be used with AI APIs
KEY TAKEAWAY

Requests is the bridge between Python and HTTP APIs.

The most important pattern to remember is: send a request, receive a response, check the response, and then process the returned data. Once you understand this pattern, working with REST APIs and eventually LLM APIs becomes much easier.