-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04_webhook_receiver_fastapi.py
More file actions
83 lines (69 loc) · 3.3 KB
/
Copy path04_webhook_receiver_fastapi.py
File metadata and controls
83 lines (69 loc) · 3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Copyright 2024-2026 Firefly Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A FastAPI app that receives flydocs webhooks and verifies them.
What it shows:
* Verifying an incoming HMAC-signed body with :class:`WebhookVerifier`.
* Parsing the typed :class:`EventEnvelope` returned by ``verifier.verify``.
* Switching on the four v1 event types
(``extraction.submitted`` / ``extraction.completed`` /
``extraction.post_processing.requested`` /
``extraction.post_processing.completed``).
* Reading the v1 ``Extraction`` + nested ``ExtractionResult`` shape.
Run it::
FLYDOCS_WEBHOOK_HMAC_SECRET=topsecret \
uv run uvicorn sdks.python.examples.04_webhook_receiver_fastapi:app --port 9000
Then point your flydocs ``callback_url`` at ``http://your-host:9000/flydocs/webhook``.
"""
from __future__ import annotations
import os
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from flydocs_sdk import (
EVENT_TYPE_EXTRACTION_COMPLETED,
EVENT_TYPE_EXTRACTION_POST_PROCESSING_COMPLETED,
EVENT_TYPE_EXTRACTION_POST_PROCESSING_REQUESTED,
EVENT_TYPE_EXTRACTION_SUBMITTED,
ExtractionStatus,
WebhookVerificationError,
WebhookVerifier,
)
verifier = WebhookVerifier(secret=os.environ["FLYDOCS_WEBHOOK_HMAC_SECRET"])
app = FastAPI()
@app.post("/flydocs/webhook")
async def on_webhook(request: Request) -> JSONResponse:
# IMPORTANT: verify against the raw body bytes -- re-encoding the
# JSON will change the digest and break the signature check.
body = await request.body()
signature = request.headers.get("X-Flydocs-Signature", "")
try:
envelope = verifier.verify(body, signature)
except WebhookVerificationError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
ext = envelope.extraction
if envelope.event_type == EVENT_TYPE_EXTRACTION_SUBMITTED:
print(f"submitted: {ext.id}")
elif envelope.event_type == EVENT_TYPE_EXTRACTION_COMPLETED:
if ext.status == ExtractionStatus.SUCCEEDED and envelope.result is not None:
for doc in envelope.result.documents:
groups = doc.field_groups
print(f" succeeded {ext.id}: {doc.type} -> {len(groups)} field groups")
elif ext.status == ExtractionStatus.FAILED and ext.error is not None:
print(f" failed {ext.id}: {ext.error.code} {ext.error.message}")
elif ext.status == ExtractionStatus.CANCELLED:
print(f" cancelled {ext.id}")
elif envelope.event_type == EVENT_TYPE_EXTRACTION_POST_PROCESSING_REQUESTED:
print(f"post-processing requested for {ext.id}")
elif envelope.event_type == EVENT_TYPE_EXTRACTION_POST_PROCESSING_COMPLETED:
print(f"post-processing completed for {ext.id}")
return JSONResponse({"ok": True})