PYTHON FOR AI • LESSON 5

REST APIs

REST APIs allow different applications to communicate with each other over HTTP. In this lesson, you will learn what a REST API is, how requests and responses work, HTTP methods, endpoints, status codes, JSON data, and how to call REST APIs using Python.

CORE IDEA

A REST API lets one application communicate with another application.

Your Python application sends an HTTP request to an API. The API processes the request and sends an HTTP response, usually containing JSON data.

01

What Is a REST API?

REST stands for Representational State Transfer.

A REST API is a way for applications to communicate through HTTP using a set of standard conventions.

For example, imagine you have a Python application and you want information about a product.

Python Application
        ↓
    HTTP Request
        ↓
    REST API
        ↓
    Database
        ↓
    REST API
        ↓
    HTTP Response
        ↓
Python Application
02

Real-World Example

Think about a weather application.

The weather application does not need to maintain its own weather database. It can ask a weather API for the current weather.

Weather App
    ↓
GET /weather
    ↓
Weather API
    ↓
Weather Data
    ↓
JSON Response
    ↓
Weather App

The API acts as the communication layer between the application and the data/service.

03

What Is an API Endpoint?

An endpoint is a specific URL where an API provides a particular resource or operation.

https://api.example.com/products

This could represent a collection of products.

Another endpoint might represent one specific product:

https://api.example.com/products/10
/products
    ↓
All products

/products/10
    ↓
Product with ID 10
04

HTTP Methods

REST APIs use HTTP methods to describe what you want to do with a resource.

  • GET — retrieve data
  • POST — create/send data
  • PUT — replace/update data
  • PATCH — partially update data
  • DELETE — delete data
GET
 ↓
Read

POST
 ↓
Create

PUT
 ↓
Replace / Update

PATCH
 ↓
Partial Update

DELETE
 ↓
Delete
05

GET Request

GET is used when you want to retrieve information.

For example:

GET /products

This could ask the API:

"Give me the products."

In Python:

import requests

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

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

POST Request

POST is commonly used when you want to send data to an API to create something.

For example:

POST /products

You might send:

{
    "name": "Laptop",
    "price": 800
}

In Python:

import requests

product = {
    "name": "Laptop",
    "price": 800
}

response = requests.post(
    "https://api.example.com/products",
    json=product
)

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

PUT and PATCH

Both methods are used to update resources, but they are not exactly the same.

PUT

PUT is generally used to replace the resource with the supplied representation.

requests.put(
    "https://api.example.com/products/10",
    json={
        "name": "New Laptop",
        "price": 900
    }
)

PATCH

PATCH is generally used when you only want to change part of a resource.

requests.patch(
    "https://api.example.com/products/10",
    json={
        "price": 900
    }
)
08

DELETE Request

DELETE is used to remove a resource.

import requests

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

print(response.status_code)

The API receives the request and can remove product 10 if the operation is allowed.

09

Request and Response

REST API communication usually has two sides: the request and the response.

CLIENT
  |
  | HTTP Request
  ↓
SERVER / API
  |
  | HTTP Response
  ↓
CLIENT

A request can contain:

  • HTTP method
  • URL
  • Headers
  • Query parameters
  • Request body

A response can contain:

  • Status code
  • Response headers
  • Response body
10

Query Parameters

Query parameters allow you to provide additional information to an API.

Example:

https://api.example.com/products?category=laptop

Here:

category=laptop
       ↑
Query parameter

In Python, Requests can build the query string for you.

import requests

params = {
    "category": "laptop"
}

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

print(response.url)
11

Path Parameters

A path parameter is part of the URL path and commonly identifies a specific resource.

/products/10

Here 10 could represent the product ID.

product_id = 10

url = f"https://api.example.com/products/{product_id}"

response = requests.get(url)
12

API Headers

Headers provide additional information about an HTTP request.

For example, an API may expect an Accept header.

import requests

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

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

print(response.json())

Authentication information is also commonly sent through headers. You will study authentication in the next topic.

13

HTTP Status Codes

The server uses a status code to tell the client what happened with the request.

  • 200 — request successful
  • 201 — resource created
  • 204 — successful request with no response body
  • 400 — bad request
  • 401 — authentication required/failed
  • 403 — forbidden
  • 404 — resource not found
  • 500 — server error
2xx
 ↓
Success

4xx
 ↓
Client-side problem

5xx
 ↓
Server-side problem
14

JSON Response

REST APIs frequently return JSON.

{
    "id": 10,
    "name": "Laptop",
    "price": 800
}

With Python Requests:

response = requests.get(url)

data = response.json()

print(data["name"])
print(data["price"])
Laptop
800
15

Complete GET Example

Let's put the important pieces together.

import requests


url = "https://api.example.com/products"

params = {
    "category": "laptop"
}

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


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


response.raise_for_status()


data = response.json()


for product in data["products"]:

    print(product["name"])
    print(product["price"])

The flow is:

Python
  ↓
GET Request
  ↓
URL + Parameters + Headers
  ↓
REST API
  ↓
HTTP Response
  ↓
JSON
  ↓
Python Dictionary/List
16

REST APIs and AI

This is particularly important for your AI journey.

Many AI services expose APIs that your Python application communicates with over HTTP.

Python AI Application
        ↓
HTTP Request
        ↓
AI REST API
        ↓
AI Service
        ↓
JSON Response
        ↓
Python Application

For example, an AI application might send a user's question to an API and receive generated text in the response.

Later, when you learn LLM APIs, you will use the same fundamental concepts: URL → HTTP method → headers → JSON request → JSON response.

17

Mini Project — Product API Client

Build a small Python program that retrieves products from an API and displays selected information.

import requests


def get_products():

    url = "https://api.example.com/products"

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

    response.raise_for_status()

    return response.json()


data = get_products()


for product in data["products"]:

    print(
        f"{product['name']} - "
        f"${product['price']}"
    )

The important thing is not the specific API URL. The goal is to understand the complete API workflow.

1. Build URL
      ↓
2. Send GET request
      ↓
3. Check response
      ↓
4. Parse JSON
      ↓
5. Extract data
      ↓
6. Display result
18

What You Learned

  • What REST APIs are
  • What API endpoints are
  • HTTP methods
  • GET requests
  • POST requests
  • PUT requests
  • PATCH requests
  • DELETE requests
  • Query parameters
  • Path parameters
  • HTTP headers
  • HTTP status codes
  • JSON API responses
  • Calling REST APIs with Python Requests
  • How REST APIs are used in AI applications
KEY TAKEAWAY

REST APIs are the bridge between your Python application and external services.

Remember the basic pattern: Python → HTTP Request → REST API → HTTP Response → JSON → Python. Once this becomes natural, working with AI APIs, LLM APIs, databases, and external services becomes much easier.