GPT Image 2 (Medium) API usage and code examples
Base URL, authentication, endpoints, and code examples for calling GPT Image 2 (Medium) (model ID: gpt-image-2-medium) through the API.
Model details
| Model ID | gpt-image-2-medium |
|---|---|
| Provider | OpenAI |
| Type | Image |
| Status | Available |
| Processing region | Global |
| Pricing | See the model page |
Base URL and authentication
| Format | Base URL | Key header |
|---|---|---|
| OpenAI | https:/ | Authorization: Bearer |
Create an API key in the console and put it in the ECHO_API_KEY environment variable.
Endpoints
| Method and path | What it does |
|---|---|
POST / | Generate images |
Call examples
Generates one image and saves it as image.png.
curl -o response.json https://token.echohub.io/v1/images/generations \
-H "Authorization: Bearer $ECHO_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2-medium",
"prompt": "A Shiba Inu walking on the beach at dusk",
"n": 1,
"size": "1024x1024",
"quality": "medium"
}'
# Save the image as image.png (works for both b64_json and url; if the request failed, response.json holds the error)
python3 -c "import json, base64, urllib.request; d = json.load(open('response.json'))['data'][0]; open('image.png', 'wb').write(base64.b64decode(d['b64_json'])) if d.get('b64_json') else urllib.request.urlretrieve(d['url'], 'image.png')"# pip install openai
import base64
import os
import urllib.request
from openai import OpenAI
client = OpenAI(
base_url="https://token.echohub.io/v1",
api_key=os.environ["ECHO_API_KEY"],
timeout=120,
)
result = client.images.generate(
model="gpt-image-2-medium",
prompt="A Shiba Inu walking on the beach at dusk",
n=1,
size="1024x1024",
quality="medium",
)
# You get either url or b64_json (depends on the model)
item = result.data[0]
if item.b64_json:
with open("image.png", "wb") as f:
f.write(base64.b64decode(item.b64_json))
else:
# Save an image returned as a url as soon as you receive it
urllib.request.urlretrieve(item.url, "image.png")
print("Saved image.png")Rules for this model
- Always set
qualitytomedium(leaving it out, or a quality that differs from the model name, returns HTTP 400) sizemust be1024x1024,1536x1024or1024x1536nmust be 1- By default the image comes back as
b64_json. Set"response_format": "url"to get the image URL (url) instead stream,partial_images,input_fidelityand image editing (/v1/images/edits) cannot be used