Print labels from FastAPI
A FastAPI endpoint can print a label after it validates the request. Depend on your own auth. The print key is a server setting.
For FastAPI services printing labels
Overview
FastAPI runs async, but the print POST is a normal HTTPS request. Use httpx or urllib in a thread. Do not await the physical printer. Return the job id to the caller.
Validate the label fields with a Pydantic model, render ZPL or PDF, then POST. Reject a missing printer_code rather than falling through to a default production printer.
BackgroundTasks can perform the POST after the response. Still use a stable idempotency key so a client retry does not double-print.
Create the job with POST /v1/print-jobs, an Authorization: Bearer header, printer_code, content_type pdf or raw, and exactly one of content or content_url. The free plan is 100 jobs a month on one computer.
Integration steps
- 01
Create an API key on the server
Use an API key (pb_live_…) in the process environment. Authorization is Bearer. Do not ship the key to browsers or mobile apps.
- 02
Install the agent beside the printer
Windows, macOS, or Linux. GET /v1/printers and keep the numeric code.
- 03
POST /v1/print-jobs
content_type is pdf or raw. Send exactly one of content (standard base64) or content_url.
- 04
Reuse the idempotency key on retry
A new key means a second physical print. HTTP 409 means the same key was reused with a different body.
- 05
Read the job before you tell the user
GET /v1/print-jobs/{id}. Paid plans can also receive print_job.completed and print_job.failed webhooks.
Python
# FastAPI: ZPL label
import json, os, urllib.request
body = json.dumps({
"printer_code": int(os.environ["PRINTER_CODE"]),
"content_type": "raw",
"content": base64.b64encode(zpl.encode()).decode(),,
"copies": 1,
}).encode()
req = urllib.request.Request(
"https://api.printbase.cloud/v1/print-jobs",
data=body,
method="POST",
headers={
"Authorization": f"Bearer {os.environ['PRINTBASE_API_KEY']}",
"Content-Type": "application/json",
"Idempotency-Key": label_id,
},
)
with urllib.request.urlopen(req) as res:
job = json.load(res) # {"id": "job_abc", "status": "queued"}
Details for this setup
Do not take the API key as a parameter
A caller who can pass the PrintBase key can print forever. Read it from the environment.
Auth
Your FastAPI dependency decides who may print. PrintBase auth is separate and uses the server key.
Questions
async def and requests?
requests is blocking. httpx.AsyncClient or a threadpool avoids blocking the event loop. The JSON is the same.
Streaming the PDF in?
UploadFile.read() gives bytes you can base64. Do not pass the UploadFile URL to the agent.
OpenAPI docs exposing the key?
Do not add the key as a header parameter in the public schema.
How is status returned?
Return the PrintBase job id. Add a second route that GETs it if the UI needs to poll.
Free plan: 100 jobs a month on one computer, no card.