C.W.K.
Stream
Lesson 03 of 07 · published

Building the Request

~22 min · request-body, headers, auth

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Both APIs use POST with JSON bodies. The key differences are in the URL and body structure.

What the SDK is hiding

When you build the request body by hand, you see the contract directly: the JSON keys (model, input, tools, instructions, max_output_tokens, stream, tool_choice) and their exact spellings. No SDK helper renamed something for you. No default snuck in that you didn't write.

This is the level at which you debug 'why does my SDK call work but my hand-rolled call return 422?' The answer is almost always one wrong field name or a missing type: "function" on a tool. Once you've built the request body manually a few times, the SDK's behavior stops feeling magical.

Code

Hand-rolled chat.completions request·python
import os, httpx

url = "https://api.openai.com/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "application/json",
}
body = {
    "model": "gpt-4.1",
    "messages": [
        {"role": "developer", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"},
    ],
    "temperature": 0.7,
    "max_completion_tokens": 1024,
}

async with httpx.AsyncClient(timeout=httpx.Timeout(connect=10, read=120, write=10, pool=5)) as client:
    resp = await client.post(url, headers=headers, json=body)
    resp.raise_for_status()
    data = resp.json()
    print(data["choices"][0]["message"]["content"])
Hand-rolled responses request with tools·python
url = "https://api.openai.com/v1/responses"
body = {
    "model": "gpt-4.1",
    "input": "Tell me a three sentence bedtime story about a unicorn.",
}
resp = await client.post(url, headers=headers, json=body)
data = resp.json()
# Access output text from response structure
print(data["output"][0]["content"][0]["text"])

External links

Exercise

Build a /v1/responses POST request body by hand for: model gpt-4.1, instructions='You are concise', input='What is 2+2?', max_output_tokens=50. Send via httpx; verify you get back response.output_text=='4'.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.