How to Call GPT-4o from Python Using HTTPX

Published 2026-09-02 · How-to

Introduction to Calling GPT-4o from Python

To interact with GPT-4o from Python, you need to send HTTP requests to OpenAI’s API endpoint. The most efficient way to do this is by using the httpx library, which offers a modern, async-friendly interface and better performance than Python’s built-in requests module. Before you start, ensure you have an OpenAI API key. For security, store your key in an environment variable rather than hardcoding it.

The basic workflow involves crafting a POST request to the GPT-4o endpoint with the correct headers and a JSON payload describing your prompt and parameters. The API responds with a JSON object containing the model’s output, which you’ll parse in your Python code.

Here’s a quick checklist for setup:

StepCommand/Action
Install httpxpip install httpx
Set API keyexport OPENAI_API_KEY=your-key-here
Import in codeimport httpx, os
You’ll need to include your API key in the Authorization header and set the Content-Type to application/json. The endpoint for GPT-4o is typically https://api.openai.com/v1/chat/completions. Handling errors gracefully is essential—always check the response status code and handle exceptions.

This approach gives you full control over the request and response cycle, supporting both synchronous and asynchronous patterns. In the next section, you’ll see a concrete example of sending your first prompt to GPT-4o using httpx.

Setting Up Your Python Environment on Ubuntu

Start by making sure your Ubuntu system has Python 3.8 or newer. Check your version with:

python3 --version

If you need to upgrade, use:

sudo apt update
sudo apt install python3 python3-pip

Next, create a clean project directory and a virtual environment. This keeps dependencies isolated:

mkdir gpt4o-httpx-demo
cd gpt4o-httpx-demo
python3 -m venv .venv
source .venv/bin/activate

Install httpx using pip. This library is fast, async-ready, and well-maintained:

pip install httpx

For security, avoid hardcoding your OpenAI API key. Instead, export it as an environment variable. Replace sk-... with your actual key:

export OPENAI_API_KEY="sk-your_actual_openai_key"

To set this variable every time you start a new shell, add the export line to your ~/.bashrc or ~/.zshrc and reload it:

echo 'export OPENAI_API_KEY="sk-your_actual_openai_key"' >> ~/.bashrc
source ~/.bashrc

Verify that your environment variable is set:

echo $OPENAI_API_KEY

You’re now ready to write Python code that securely accesses your API key and makes requests to GPT-4o using HTTPX. This setup ensures your credentials stay out of source code and version control.

Installing HTTPX and Required Libraries

To interact with the GPT-4o API, you'll need the httpx library for HTTP requests and python-dotenv to manage your API key securely. Install both inside your virtual environment to avoid polluting your system Python.

Activate your virtual environment first:

source .venv/bin/activate

Now install the required libraries:

pip install httpx python-dotenv

httpx is a modern alternative to requests, supporting both synchronous and asynchronous code. python-dotenv lets you load environment variables from a .env file, which is the recommended way to manage sensitive credentials like your OpenAI API key.

Create a .env file in your project directory and add your API key:

OPENAI_API_KEY=sk-...

Ensure this file is not tracked by version control by adding it to your .gitignore:

.env

With these libraries installed and your API key set, you’re ready to write Python code that securely calls the GPT-4o endpoint. This setup is minimal but robust for most use cases.

Obtaining Your OpenAI API Key

To use the GPT-4o API, you need a personal API key from OpenAI. This key authenticates your requests and tracks your usage. Visit https://platform.openai.com/api-keys and log in with your OpenAI account. Click "Create new secret key" to generate a fresh key. Copy it immediately—OpenAI won’t show it again.

Storing your API key securely is critical. Never hardcode it in your scripts or commit it to version control. The recommended approach is to use an environment variable. On Ubuntu, you can set this in your shell session:

export OPENAI_API_KEY='sk-...yourkeyhere...'

For persistent usage, add the above line to your ~/.bashrc or ~/.zshrc file and reload your shell:

source ~/.bashrc

Alternatively, store the key in a .env file in your project directory if you’re using python-dotenv. Create a file named .env and add:

OPENAI_API_KEY=sk-...yourkeyhere...

This lets your Python code load the key at runtime without exposing it in your source. Pick one method that best fits your workflow, but always keep your API key private and never share it. If you suspect your key has leaked, revoke it immediately from your OpenAI dashboard.

Writing Python Code to Call GPT-4o with HTTPX

With your environment ready and dependencies installed, it’s time to write Python code that calls the GPT-4o API using HTTPX. Start by creating a .env file in your project directory containing your OpenAI API key:

OPENAI_API_KEY=sk-...

Now, create a main.py file. Load your API key using python-dotenv, then craft an HTTPX POST request to the GPT-4o endpoint. Always use HTTPS and set the authorization header. Below is a minimal, robust example:

import httpx
import os
from dotenv import load_dotenv

load_dotenv()
API_KEY = os.getenv("OPENAI_API_KEY")
assert API_KEY, "API key not found in environment variables"

url = "https://api.openai.com/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}
payload = {
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Hello, GPT-4o!"}]
}

try:
    response = httpx.post(url, headers=headers, json=payload, timeout=30)
    response.raise_for_status()
    data = response.json()
    print(data["choices"][0]["message"]["content"].strip())
except Exception as e:
    print(f"API call failed: {e}")

This snippet demonstrates best practices: environment-based secrets, error handling, and parsing the API’s JSON response. Adjust the messages payload to suit your use case. For production, consider async HTTPX for better concurrency.

Handling and Parsing GPT-4o Responses

Once you receive a response from the GPT-4o API, it arrives as JSON. You must parse this to extract the model’s generated text and handle any errors gracefully. The structure of the response typically includes a choices list, where each item contains a message with a content field holding the model's output.

Here’s a concise way to parse and handle the response using Python:

import httpx

response = client.post(
    "https://api.openai.com/v1/chat/completions",
    headers=headers,
    json=payload,
    timeout=30,
)

if response.status_code != 200:
    print(f"Error: {response.status_code} {response.text}")
    raise RuntimeError("Failed to get a valid response from GPT-4o")

data = response.json()
try:
    message = data["choices"][0]["message"]["content"]
    print("GPT-4o says:", message)
except (KeyError, IndexError):
    print("Unexpected response format:", data)
    raise

Always check the HTTP status code before parsing. If the API returns a non-200 status, log the error and halt further processing. When extracting the model’s output, wrap your parsing logic in a try/except block to catch unexpected response formats—this is crucial since API responses can change or include error messages.

For advanced use cases, you might want to handle additional fields like usage (for token counts) or finish_reason (to detect truncation). Here’s a quick reference for the top-level response fields:

FieldDescription
choicesList of model outputs
usageToken usage statistics
idUnique identifier for the API call
createdTimestamp of the response
modelThe model used (e.g., gpt-4o)
By handling responses defensively, you ensure your application remains robust and easy to debug.

Error Handling and Troubleshooting

When working with GPT-4o via HTTPX, always anticipate possible errors and handle them gracefully. OpenAI's API can return different error codes, such as 401 for authentication issues, 429 for rate limits, and 500 for server errors. Failing to check responses can result in cryptic bugs or unhandled exceptions.

Wrap your API call in a try-except block to catch network timeouts and HTTP errors. Always check the response status code before parsing JSON. Here’s a robust pattern:

import httpx

try:
    response = httpx.post(
        "https://api.openai.com/v1/chat/completions",
        headers={"Authorization": f"Bearer {api_key}"},
        json=payload,
        timeout=30,
    )
    response.raise_for_status()
    data = response.json()
except httpx.HTTPStatusError as exc:
    print(f"HTTP error {exc.response.status_code}: {exc.response.text}")
except httpx.RequestError as exc:
    print(f"Request failed: {exc}")
except Exception as exc:
    print(f"Unexpected error: {exc}")

If you get a 401, double-check your API key and environment variable. For 429 errors, slow down your requests—OpenAI enforces strict rate limits. If you see a 500-series error, retry after a short delay; these are usually temporary.

For debugging, log both the status code and response body. This will help you distinguish between authentication, payload formatting, and server-side problems. Avoid printing your API key in error messages to keep it secure.

If errors persist, consult the OpenAI API status page and check your account’s usage limits. Proper error handling ensures your application fails gracefully and is easier to maintain.

Best Practices for Secure API Usage

When using the GPT-4o API, it's crucial to handle your API key securely to prevent unauthorized access. Set your OpenAI API key as an environment variable on Ubuntu using the export command. For persistent storage, add this line to your ~/.bashrc file or use a .env file with python-dotenv.

To further secure your API usage, always verify the SSL certificates of the API endpoint. The httpx library does this by default, but you can explicitly set the verify parameter to True for clarity.

Here's how you might structure your API call with secure practices in mind:

import httpx
import os

api_key = os.getenv("OPENAI_API_KEY")
url = "https://api.openai.com/v1/completions"

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

# Your JSON payload here
payload = {
    "model": "gpt-4o",
    "prompt": "Your prompt text",
    "max_tokens": 2048
}

response = httpx.post(url, headers=headers, json=payload, verify=True)

Regularly review OpenAI's API terms and usage guidelines to ensure compliance. Also, monitor your API usage and adjust your prompts and parameters to optimize performance and minimize costs.

FAQ

How do I call the GPT-4o model from Python using HTTPX?

To call GPT-4o from Python using HTTPX, you need to send a POST request to the OpenAI API endpoint with the appropriate headers and JSON payload. Use HTTPX to set the 'Authorization' header with your API key, specify 'application/json' content type, and include the model name 'gpt-4o' in the request body under the 'model' field. The payload should contain your prompt and any other parameters like max_tokens. Then, parse the JSON response to get the generated text.

Can you provide a simple Python example using HTTPX to send a request to GPT-4o?

Certainly! Here's a basic example: import httpx; define headers with your API key and content-type; create a JSON payload specifying 'model': 'gpt-4o' and your prompt; then send a POST request to 'https://api.openai.com/v1/chat/completions'. For example, use httpx.post(url, headers=headers, json=payload). Finally, parse the response JSON to extract the generated message. This approach leverages HTTPX's async or sync client to interact with the GPT-4o API.

What is the required JSON structure to send a chat completion request to GPT-4o using HTTPX?

When sending a chat completion request to GPT-4o, the JSON payload must include the 'model' key set to 'gpt-4o' and a 'messages' array. Each message is an object with 'role' (like 'user' or 'system') and 'content' (the text prompt). For example: {"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello!"}]}. This structure is required to properly format the conversation and receive a valid response from the API.

How do I handle authentication when calling OpenAI GPT-4o API with HTTPX in Python?

Authentication is handled via an API key provided by OpenAI. When using HTTPX, include an 'Authorization' header with the value 'Bearer YOUR_API_KEY'. For example, headers = {"Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json"}. Replace 'YOUR_API_KEY' with your actual key. This header must be included in every request to authenticate and authorize your access to the GPT-4o API.

Are there any best practices for error handling when sending requests to GPT-4o using HTTPX in Python?

Yes, when using HTTPX to call GPT-4o, implement error handling by checking the response status code. If the status code is not 200, handle exceptions gracefully, such as logging the error or retrying the request. You can also catch HTTPX exceptions like httpx.RequestError for network issues. Additionally, parse the error message from the API response JSON to understand issues like invalid parameters or rate limits. This ensures your application can recover or inform users appropriately.

Related reading