Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

API Requests in Python

Python can send HTTP requests to APIs, receive responses, and work with data returned by web services.

What are API Requests?

An API request is a communication sent from one application to another application through an API.

Python can send requests to REST APIs to retrieve data, create records, update information, or delete resources.

Simple Definition

An API request is a request sent by a client application to an API endpoint to perform an operation or retrieve data.

API Request Flow

Python Client

Python application creates a request.

→
API Server

API receives and processes the request.

→
API Response

Server returns status, headers, and data.

Python Requests Library

The requests library is commonly used in Python programs to send HTTP requests.

Install it using:

pip install requests
Tip: Use a virtual environment for project dependencies.

Basic GET Request

A GET request is commonly used to retrieve information from an API.

import requests

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

print(response.status_code)
print(response.text)

The response object contains information returned by the server.

Understanding the Response Object

status_code

Returns the HTTP status code.

response.status_code
text

Returns the response content as text.

response.text
json()

Converts a JSON response into Python data.

response.json()

Reading JSON Response

Many REST APIs return data in JSON format. The json() method can be used to read it.

import requests

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

response = requests.get(url)

data = response.json()

print(data)

Sending Headers

Headers can provide additional information with an API request.

import requests

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

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

response = requests.get(
    url,
    headers=headers
)

print(response.json())

Sending Query Parameters

Query parameters can be sent using the params argument.

import requests

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

params = {
    "city": "Pune"
}

response = requests.get(
    url,
    params=params
)

print(response.json())
The requests library builds the query string from the supplied parameters.

POST Request

POST is commonly used to send data to an API and create a new resource.

import requests

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

student = {
    "name": "Rahul",
    "course": "Python"
}

response = requests.post(
    url,
    json=student
)

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

PUT Request

PUT can be used to update an existing resource.

import requests

url = "https://api.example.com/students/1"

student = {
    "name": "Rahul",
    "course": "FastAPI"
}

response = requests.put(
    url,
    json=student
)

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

DELETE Request

DELETE is used to remove a resource from an API.

import requests

url = "https://api.example.com/students/1"

response = requests.delete(url)

print(response.status_code)

Common API Requests in Python

Python Method HTTP Method Common Purpose
requests.get() GET Retrieve data
requests.post() POST Create data
requests.put() PUT Update data
requests.delete() DELETE Delete data

Checking Status Codes

Always check the response status before processing important API data.

import requests

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

if response.status_code == 200:
    print("Request successful")
else:
    print("Request failed")

Handling HTTP Errors

The raise_for_status() method raises an exception when the response contains an HTTP error status.

import requests

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

response.raise_for_status()

print(response.text)

Using a Timeout

A timeout prevents the program from waiting indefinitely for a server response.

import requests

response = requests.get(
    "https://example.com",
    timeout=10
)

print(response.status_code)
Setting a suitable timeout is a useful practice for network-based applications.

Handling Request Exceptions

Network problems can occur while communicating with an external API. Python can handle request-related exceptions using try and except.

import requests

try:
    response = requests.get(
        "https://example.com",
        timeout=10
    )

    response.raise_for_status()

    print(response.json())

except requests.RequestException as error:
    print("Request failed:", error)

Example: Reading Student Data 🤓📩

The following example demonstrates how a Python program can request student data from an API.

import requests

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

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

    response.raise_for_status()

    students = response.json()

    for student in students:
        print(student)

except requests.RequestException as error:
    print("Unable to fetch students:", error)

Example JSON Response

Suppose an API returns the following JSON data:

{
    "id": 101,
    "name": "Rahul",
    "course": "Python",
    "city": "Pune"
}

Python can read individual values from the returned data.

data = response.json()

print(data["name"])
print(data["course"])

Main Parts of an API Request

URL

Identifies the API endpoint.

Method

Defines the requested operation.

Headers

Provide additional request information.

Parameters

Provide extra values required by the API.

Request Body

Contains data sent to the server.

Response

Contains status and returned data.

Tools Used for API Testing

  • Postman
  • Swagger UI
  • Browser
  • cURL
  • Python requests library

Best Practices

  • Use clear and valid API URLs.
  • Always check response status codes.
  • Use timeouts for external requests.
  • Handle request exceptions.
  • Validate API response data before using it.
  • Keep API keys and credentials secure.

Common Mistakes

  • Using an incorrect API URL.
  • Forgetting to install the requests library.
  • Not checking the response status.
  • Not handling network errors.
  • Waiting indefinitely because no timeout was specified.
  • Exposing API credentials in source code.

Practice Exercise

Create a Python program that:

  1. Sends a GET request to an API.
  2. Prints the response status code.
  3. Converts the response into JSON.
  4. Prints selected values from the JSON response.
  5. Handles request errors using try and except.
  6. Uses a timeout for the request.

Test the program using a public API or a local API created with FastAPI.

Summary

Python can communicate with APIs using HTTP requests. The requests library is commonly used for API communication, while GET retrieves data, POST creates data, PUT updates data, and DELETE removes data. JSON responses can be converted into Python data, and status codes, timeouts, and exceptions should be handled properly when working with APIs.