OpenAI webhooks let the API call your server when a long job finishes. You stop polling and get a signed HTTP POST the moment a background response, batch or fine-tuning job is done.
This guide builds a working receiver in Python with FastAPI and Flask. It covers dashboard setup, every current event type, signature checks with unwrap(), retries, duplicates, local testing and real error messages.
- What it is: OpenAI sends a POST with a small JSON event (type plus an object ID) to your HTTPS URL when something happens in your project.
- Setup: create an endpoint in the dashboard webhook settings, or with
client.webhooks.create(). Save the signing secret, because it is shown only once. - Verify: call
client.webhooks.unwrap(raw_body, headers). It checks the signature and a 300-second timestamp window, then returns a typed event. - Retries: no 2xx within a few seconds means a retry, with exponential backoff for up to 72 hours. Redirects count as failures.
- Duplicates: use the
webhook-idheader as an idempotency key. - SDK checked:
openai3.65.0 for Python (5 Dec 2026), which lists 29 event types you can subscribe to.
What OpenAI Webhooks Are and When to Use Them
Some OpenAI jobs take minutes or hours. A batch can run for up to a day, and a background response from a big reasoning model can take a long time too.
Without webhooks, your code has to ask “is it done yet?” again and again. With webhooks, OpenAI tells you. Your server gets one small POST, and then it fetches the full result with the ID in the event.

background=True responses, Batch API jobs, fine-tuning, evals, video jobs and incoming SIP calls for the Realtime API. Keep normal calls or streaming for chat that a user is watching.Webhooks follow the open Standard Webhooks specification. That matters, because any Standard Webhooks library can verify them, not only the OpenAI SDK.
New to these job types? Read my OpenAI Responses API tutorial for background mode and the OpenAI Batch API tutorial for batch files. Webhooks are the “done” signal for both.
Every Webhook Event Type (December 2026)
I read the event list straight from the official Python SDK, version 3.65.0. The create and update methods accept 29 event types. The API reference page I fetched still listed 27, so health alerts (announced 3 December 2026) look like the newest addition.
| Group | Event types | Fires when | data holds |
|---|---|---|---|
| Background responses | response.completed, response.failed, response.cancelled, response.incomplete |
A background=True response finishes, fails, is cancelled or is interrupted |
id (the resp_ ID) |
| Batch | batch.completed, batch.failed, batch.expired, batch.cancelled |
A Batch API job reaches a final state | id (the batch ID) |
| Fine-tuning | fine_tuning.job.succeeded, fine_tuning.job.failed, fine_tuning.job.cancelled |
A fine-tuning job ends | id (the job ID) |
| Evals | eval.run.succeeded, eval.run.failed, eval.run.canceled |
An eval run ends (note the US spelling “canceled” here) | id (the run ID) |
| Realtime calls | realtime.call.incoming |
An incoming SIP call is waiting to be accepted | call_id, sip_headers, sip_media_security |
| Video | video.completed, video.failed |
A video generation job ends | Not modeled in the Python SDK yet (check the API reference) |
| Agents API environments | agent.environment.ready, .failed, .suspended, .expired |
An agent environment changes state | id (the environment ID) |
| Agents API sessions | agent.session.created, .action_required, .in_progress, .idle, .failed |
A session changes state or needs an approval or tool result | id, plus required_action on action_required |
| Health alerts | health.alert.triggered, health.alert.resolved |
An API health metric crosses a threshold, or recovers | A notification id |
| Safety | safety.alert.created |
An approved safety alert is ready for a project | id (the alert ID) |
The SDK can also parse a few events that you do not pick in the endpoint form. These include live.call.incoming, live.transport.incoming, live.transport.connected and organization safety notices such as safety.warning_issued. OpenAI covers those in separate guides.
Tip: event lists change often. Call client.webhooks.event_types.list() to see exactly which types your project can use today.
What a Webhook Request Looks Like
Every delivery is an HTTP POST with a JSON body. The body is tiny on purpose. It tells you what happened and which object, and you fetch the full object yourself.
POST https://yourserver.com/webhook
user-agent: OpenAI/1.0 (+https://platform.openai.com/docs/webhooks)
content-type: application/json
webhook-id: wh_685342e6c53c8190a1be43f081506c52
webhook-timestamp: 1750287078
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=
{
"object": "event",
"id": "evt_685343a1381c819085d44c354e1b330e",
"type": "response.completed",
"created_at": 1750287018,
"data": { "id": "resp_abc123" }
}
The three webhook-* headers do the security work:
webhook-id: a unique ID for this message. Retries of the same message keep the same ID, so it is your dedupe key.webhook-timestamp: Unix seconds when it was sent. The SDK rejects anything more than 300 seconds old or in the future.webhook-signature: one or morev1,<base64>values. Each is an HMAC-SHA256 ofid.timestamp.bodyusing your secret.
Set Up an Endpoint in the Dashboard
Webhook endpoints belong to a project. Pick the right project in the dashboard first, because events from other projects will not reach this URL.
- Install the SDK. Run
pip install -U openai(Python 3.10 or newer) plusfastapi uvicornorflask. - Get a public HTTPS URL. Deploy your receiver, or use a tunnel such as ngrok while you develop (see the local testing section).
- Open webhook settings. Sign in to the OpenAI platform dashboard, choose your project, and open the Webhooks page in the project settings.
- Click Create. Enter a name (for your reference only), your public URL such as
https://api.example.com/webhook, and the event types you want. - Copy the signing secret. You cannot view it again after this screen. Store it as
OPENAI_WEBHOOK_SECRETon your server. - Send a test event. Use the test option on the webhook settings page. Your server should log the event and answer with HTTP 200.
- Trigger a real event. Start a background response or a small batch (Example 3) and watch for the delivery.
Warning: never paste the signing secret into code or Git. If it leaks, rotate it from the webhook settings page or with rotate_secret() straight away.
Example 1: A FastAPI Receiver
This receiver verifies the signature, drops duplicates using SQLite, and does the slow work after the 200 is sent. Set OPENAI_API_KEY and OPENAI_WEBHOOK_SECRET, then run uvicorn app:app --port 8000.
import sqlite3
from fastapi import BackgroundTasks, FastAPI, Request, Response
from openai import InvalidWebhookSignatureError, OpenAI
client = OpenAI() # reads OPENAI_API_KEY and OPENAI_WEBHOOK_SECRET
app = FastAPI()
db = sqlite3.connect("webhooks.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS seen (webhook_id TEXT PRIMARY KEY)")
def first_time(webhook_id: str) -> bool:
"""Return True only the first time we see this webhook-id."""
try:
with db:
db.execute("INSERT INTO seen (webhook_id) VALUES (?)", (webhook_id,))
return True
except sqlite3.IntegrityError:
return False
def handle_event(event) -> None:
if event.type == "response.completed":
resp = client.responses.retrieve(event.data.id)
print("Response ready:", resp.output_text[:200])
elif event.type in ("response.failed", "response.incomplete"):
print("Response problem:", event.type, event.data.id)
elif event.type == "batch.completed":
batch = client.batches.retrieve(event.data.id)
print("Batch done, output file:", batch.output_file_id)
else:
print("Ignoring event type:", event.type)
@app.post("/webhook")
async def webhook(request: Request, tasks: BackgroundTasks):
body = await request.body() # raw bytes, never request.json()
try:
event = client.webhooks.unwrap(body, request.headers)
except (InvalidWebhookSignatureError, ValueError):
return Response("invalid signature", status_code=400)
if first_time(request.headers["webhook-id"]):
tasks.add_task(handle_event, event)
return Response(status_code=200)
Two details matter here. First, unwrap() must get the raw body, because parsing and re-encoding JSON changes the bytes and breaks the signature.
Second, I catch ValueError as well. The SDK raises a plain ValueError when a header is missing, and InvalidWebhookSignatureError is itself a subclass of it.
Example 2: A Flask Receiver
Flask works the same way. Use request.get_data() for the raw bytes. The in-memory set is fine for a demo, but it forgets everything on restart, so use Redis or a database in production.
import threading
from flask import Flask, request
from openai import InvalidWebhookSignatureError, OpenAI
app = Flask(__name__)
client = OpenAI() # uses OPENAI_WEBHOOK_SECRET by default
seen_ids = set() # demo only: use Redis or a database in production
def process(event):
if event.type == "response.completed":
resp = client.responses.retrieve(event.data.id)
print("Output:", resp.output_text[:200])
elif event.type == "fine_tuning.job.succeeded":
job = client.fine_tuning.jobs.retrieve(event.data.id)
print("New model:", job.fine_tuned_model)
@app.post("/webhook")
def webhook():
raw = request.get_data() # raw bytes, exactly as sent
try:
event = client.webhooks.unwrap(raw, request.headers)
except (InvalidWebhookSignatureError, ValueError) as err:
print("Rejected:", err)
return "invalid signature", 400
webhook_id = request.headers["webhook-id"]
if webhook_id in seen_ids:
return "", 200 # duplicate delivery, already handled
seen_ids.add(webhook_id)
threading.Thread(target=process, args=(event,), daemon=True).start()
return "", 200
if __name__ == "__main__":
app.run(port=8000)
Both receivers were run locally with a self-signed test event: a valid signature returned 200 and a request with no signature returned 400.
Verify without parsing
If you want to check the signature but parse the JSON yourself, call client.webhooks.verify_signature(raw, request.headers). It raises the same errors and returns nothing. It also takes a tolerance argument, which defaults to 300 seconds.
Example 3: Trigger Real Events
Your endpoint is ready, so now make OpenAI send something. The quickest event is response.completed from a background response.
from openai import OpenAI
client = OpenAI()
resp = client.responses.create(
model="gpt-6.2-sol",
input="Write a 1,000-word guide to caring for a sourdough starter.",
background=True,
)
print(resp.id, resp.status) # e.g. resp_... queued
# Optional: a batch job sends batch.completed when it ends
batch_file = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
input_file_id=batch_file.id,
endpoint="/v1/responses",
completion_window="24h",
)
print(batch.id, batch.status)
Your receiver gets the event when the job ends. It then calls responses.retrieve() or batches.retrieve() to load the full result. For how long these jobs may take, see my guide to OpenAI background completion windows.
Incoming SIP calls
For phone calls through the Realtime API, realtime.call.incoming carries a call_id. Pass it unchanged to client.realtime.calls.accept(call_id, type="realtime", model=...) or to reject(). My OpenAI Realtime API guide covers the session setup.
Example 4: Manage Endpoints From Code (Plus curl)
You no longer need the dashboard for everything. SDK 3.65.0 has full endpoint management under client.webhooks.
from openai import OpenAI
client = OpenAI()
print(client.webhooks.event_types.list().data) # types this project can use
ep = client.webhooks.create(
name="prod-receiver",
url="https://api.example.com/webhook",
event_types=["response.completed", "response.failed", "batch.completed"],
)
print(ep.id)
# ep.signing_secret is returned only now: save it to your secret store
result = client.webhooks.test(ep.id, event_type="batch.completed")
print("Endpoint answered with HTTP", result.status_code)
new = client.webhooks.rotate_secret(ep.id, keep_old_secret_active_for_24_hours=True)
# new.signing_secret: deploy it, the old one keeps working for 24 hours
The same client also has list(), retrieve(), update() and delete(). Note that update(event_types=...) replaces the whole list, so send every type you want to keep.
Here is the create call with curl:
curl https://api.openai.com/v1/webhook_endpoints \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"name": "prod-receiver",
"url": "https://api.example.com/webhook",
"event_types": ["batch.completed"]
}'
Retries, Timeouts and Idempotency
OpenAI treats anything other than a quick 2xx as a failed delivery. The official rules are short and strict.
- Respond fast: return 2xx within a few seconds. Slow handlers get retried even if they finish later.
- Retry window: failed deliveries are retried with exponential backoff for up to 72 hours.
- No redirects: a 3xx response is a failure. Register the final URL, including the right trailing slash.
- Duplicates happen: OpenAI says it may rarely send the same event twice, so dedupe on
webhook-id.

A simple pattern covers all of this. Verify, store the webhook-id, return 200, and push the real work to a queue or background task.
Note: do not return 400 or 500 for events you simply do not handle. Return 200, or OpenAI will keep retrying an event you never wanted.
Do not trust event order
Retries mean a response.failed could arrive after a later event, or an old event could arrive late. Always fetch the object by its ID and act on its current status, not just on the event type.
Test Webhooks Locally
OpenAI can only reach a URL on the public internet. OpenAI’s guide suggests ngrok, or cloud dev setups such as Replit, GitHub Codespaces, Cloudflare Workers or v0 from Vercel.
- Start your app. Run
uvicorn app:app --port 8000orpython app.py. - Open a tunnel. Run
ngrok http 8000and copy the HTTPS forwarding URL. - Register the URL. Add
/webhookto it and save it as the endpoint URL, in the dashboard or withupdate(). - Send a test event. Use the dashboard test button or
client.webhooks.test().
Offline test with a self-signed event
You can also test with no tunnel at all. This script signs a fake event with your test secret, exactly the way the Standard Webhooks spec describes, and posts it to your local server.
import base64, hashlib, hmac, json, os, time, uuid
import urllib.request
secret = os.environ["OPENAI_WEBHOOK_SECRET"] # use a test secret
key = base64.b64decode(secret.removeprefix("whsec_"))
body = json.dumps({
"object": "event",
"id": "evt_test_123",
"type": "batch.completed",
"created_at": int(time.time()),
"data": {"id": "batch_test_123"},
})
msg_id = "wh_" + uuid.uuid4().hex
ts = str(int(time.time()))
signed = f"{msg_id}.{ts}.{body}".encode()
sig = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
req = urllib.request.Request(
"http://127.0.0.1:8000/webhook",
data=body.encode(),
headers={
"content-type": "application/json",
"webhook-id": msg_id,
"webhook-timestamp": ts,
"webhook-signature": "v1," + sig,
},
)
print(urllib.request.urlopen(req).status) # 200 means verify passed
Cost and Limits
OpenAI’s pricing page does not list any charge for webhook deliveries. You pay for the jobs that create the events, at normal token prices. Prices below come from the official pricing page, checked on 5 December 2026.
| Model | Standard input / output per 1M | Batch input / output per 1M |
|---|---|---|
GPT-6.2 Sol (gpt-6.2-sol) |
$2.00 / $10.00 | $1.00 / $5.00 |
GPT-6.2 Astra (gpt-6.2-astra) |
$8.00 / $40.00 | $4.00 / $20.00 |
Worked example: a batch of 2,000 requests, each with 1,500 input and 500 output tokens on GPT-6.2 Sol. That is 3M input tokens ($3.00) plus 1M output tokens ($5.00), so $8.00 at batch rates instead of $16.00 standard. The single batch.completed webhook replaces hours of polling.
These are the webhook limits I could confirm in the official docs and the SDK source:
| Limit | Value |
|---|---|
| Response deadline | A 2xx within “a few seconds” |
| Retry window | Up to 72 hours, exponential backoff |
| Signature timestamp tolerance (SDK) | 300 seconds, either direction |
| URL scheme | HTTPS, public internet, no redirects |
| Signing secret visibility | Shown once, at creation or rotation |
| Old secret after rotation | Invalid at once, or 24 hours with keep_old_secret_active_for_24_hours |
| Endpoint list page size | 20 by default (limit to change) |
| Scope | One project per endpoint |
Security Checklist
Verification is optional in the SDK, but OpenAI says you should verify, especially if a webhook triggers any action. Treat every unverified request as hostile.
- Always verify: call
unwrap()orverify_signature()before any work, and return 400 on failure. - Fetch, do not trust: the event only carries an ID. Load the object with your API key so a forged body can never inject data.
- Keep the timestamp check: do not raise
tolerancemuch. The 300-second window blocks replays of old captured requests. - Store secrets safely: keep
OPENAI_WEBHOOK_SECRETin your secret manager and rotate it if it leaks. - Treat SIP headers as untrusted: the SDK docs warn that
sip_headerson call events are untrusted metadata. - Log safely: log event IDs and types, not secrets or full model outputs with user data.
For key handling in general, see how to get an OpenAI API key and my OpenAI API Python tutorial.
Troubleshooting: Common Problems and Fixes
These messages come straight from the SDK source (openai 3.65.0), plus delivery problems from the official guide.
| Error or symptom | Cause | Fix |
|---|---|---|
The given webhook signature does not match the expected signature |
Wrong secret, wrong project, or the body was parsed before verifying | Pass raw bytes (await request.body() or request.get_data()) and the secret for this exact endpoint |
Webhook timestamp is too old / too new |
Server clock is off, or a replayed request | Sync the clock with NTP; do not replay old captures |
Could not find webhook-signature header |
A proxy stripped headers, or the request did not come from OpenAI | Forward all webhook-* headers through your load balancer |
The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET... |
No secret configured | Set the env var, pass OpenAI(webhook_secret=...), or pass secret= |
| Events arrive twice | Retries or a rare duplicate delivery | Dedupe on webhook-id |
| Endless retries, handler runs many times | Handler is slow, so OpenAI times out | Return 200 first, then process in the background |
| No events at all | Endpoint in another project, URL redirects, or event type not selected | Check project, use the final HTTPS URL, and run a test event |
Frequently Asked Questions
Do OpenAI webhooks cost extra?
OpenAI’s pricing page lists no charge for webhook deliveries. You pay only for the background responses, batches or other jobs that trigger them.
Which OpenAI jobs can send webhooks?
Background responses, Batch API jobs, fine-tuning, eval runs, video jobs, Realtime SIP calls, Agents API sessions and environments, health alerts and safety alerts. The Python SDK 3.65.0 lists 29 subscribable types.
Is signature verification required?
No, but OpenAI strongly recommends it. Without it, anyone who finds your URL can send fake events.
How long does OpenAI retry a failed webhook?
Up to 72 hours with exponential backoff. Any non-2xx answer, a slow answer or a redirect counts as a failure.
Can I use webhooks without a public server?
Not for real deliveries, because OpenAI must reach your URL over the internet. During development, a tunnel such as ngrok or a cloud dev environment works.
Can I create webhook endpoints with the API?
Yes. The SDK has client.webhooks.create(), plus update(), test(), rotate_secret(), list() and delete(), all on /v1/webhook_endpoints.
Do webhooks work with streaming responses?
Webhooks are for work that runs in the background. If you stream a response to a user, you already get the result live, so a webhook adds nothing there.



