justapi — /docs

JustAPI ships native response classes — HTMLResponse, PlainTextResponse, JSONResponse, RedirectResponse, StreamingResponse, and FileResponse — imported directly from justapi. Return them from any handler to override the default JSON serialization.

HTML Response

from justapi import HTMLResponse, JustAPIApp

app = JustAPIApp()

@app.get("/html")
def html_page():
    return HTMLResponse(content="<h1>Hello</h1><p>This is HTML</p>")

Plain Text Response

from justapi import PlainTextResponse

@app.get("/text")
def text():
    return PlainTextResponse("Hello, plain text!")

JSON Response with Custom Headers

from justapi import JSONResponse

@app.get("/custom")
def custom():
    return JSONResponse(
        content={"data": "value"},
        headers={"X-Custom": "header-value"},
    )

Streaming Response

from justapi import StreamingResponse

async def generate_tokens():
    for i in range(10):
        yield f"data: token_{i}\n\n"
        import asyncio
        await asyncio.sleep(0.1)

@app.get("/stream")
def stream():
    return StreamingResponse(generate_tokens(), media_type="text/event-stream")

JustAPI also ships a dedicated TokenStreamResponse for LLM token streaming (see Streaming Output).

Redirect

from justapi import RedirectResponse

@app.get("/old-path")
def old_path():
    return RedirectResponse(url="/new-path", status_code=302)

@app.get("/new-path")
def new_path():
    return {"message": "you are here"}

File Response

from justapi import FileResponse

@app.get("/download")
def download():
    return FileResponse("report.pdf", filename="report.pdf")

FileResponse reads the file eagerly into memory; the media type is inferred from the file extension unless media_type is given.

Custom Response Class

Subclass a native response and override render:

from justapi import JSONResponse

class PrettyJSONResponse(JSONResponse):
    def render(self, content) -> bytes:
        import json
        return json.dumps(
            content,
            indent=2,
            ensure_ascii=False,
        ).encode("utf-8")

@app.get("/pretty")
def pretty():
    return PrettyJSONResponse(content={"data": "value"})

Response + Status Code

Set a non-default status by returning a response object with an explicit status_code (the route-decorator status_code= kwarg is OpenAPI metadata, not applied to the response):

from justapi import JSONResponse

@app.post("/items")
def create_item():
    return JSONResponse(content={"message": "created"}, status_code=201)

See Also

JustAPI v2.0.9 — Open Source MIT License · Built with WebTUI · GitHub

NORMAL master justapi/docs
utf-8 Top 1:1