Response Classes
JustAPI provides several response classes optimized for zero-copy data transfer from Rust to Python.
Response
Section titled “Response”Base response class:
from justapi.responses import Response
return Response( content="Hello", status_code=200, headers={"X-Custom": "value"},)| Parameter | Type | Default | Description |
|---|---|---|---|
content |
str |
"" |
Response body text |
status_code |
int |
200 |
HTTP status code |
headers |
dict |
None |
Additional headers |
JSONResponse
Section titled “JSONResponse”Automatically serializes a Python object to JSON using Rust’s serde_json:
from justapi.responses import JSONResponse
return JSONResponse({"message": "Hello", "items": [1, 2, 3]})| Parameter | Type | Default | Description |
|---|---|---|---|
content |
dict or list |
required | Python object to serialize |
HTMLResponse
Section titled “HTMLResponse”Sets Content-Type: text/html:
from justapi.responses import HTMLResponse
return HTMLResponse("<h1>Hello</h1>")PlainTextResponse
Section titled “PlainTextResponse”Sets Content-Type: text/plain:
from justapi.responses import PlainTextResponse
return PlainTextResponse("Hello, World!")RedirectResponse
Section titled “RedirectResponse”Returns an HTTP redirect:
from justapi.responses import RedirectResponse
return RedirectResponse( url="https://example.com", status_code=307, # Temporary redirect)| Parameter | Type | Default | Description |
|---|---|---|---|
url |
str |
required | Redirect target URL |
status_code |
int |
307 |
Redirect status (307, 308, 301, 302) |
StreamingResponse
Section titled “StreamingResponse”Streams content using a Python generator:
from justapi.responses import StreamingResponseimport asyncio
@app.get("/stream")async def stream(request): async def generate(): for i in range(100): yield f"data: {i}\n\n" await asyncio.sleep(0.1)
return StreamingResponse(generate(), media_type="text/plain")| Parameter | Type | Default | Description |
|---|---|---|---|
generator |
async generator | required | Content generator |
media_type |
str |
"text/plain" |
Content-Type header |
Dict Return (Shortcut)
Section titled “Dict Return (Shortcut)”When a route handler returns a plain dict, it’s automatically converted to JSONResponse:
@app.get("/")def handler(request): return {"message": "Hello"} # Equivalent to JSONResponse(...)Setting Status Codes
Section titled “Setting Status Codes”Use tuples or the status key in the response dict for non-200 status codes:
@app.post("/items")def create_item(request): return {"status": 201, "body": {"id": 1, "name": "Item"}}The status key sets the HTTP status code, while body contains the response body.
See Also
Section titled “See Also”- Request Object — Accessing request data
- Streaming Output — Validated streaming with
@app.stream_json - Error Handling — Error response patterns