Custom Response Classes
Using response_class in Decorator
Section titled “Using response_class in Decorator”Set the response class directly in the decorator:
from starlette.responses import HTMLResponse, PlainTextResponsefrom justapi import JustAPIApp
app = JustAPIApp()
@app.get("/", response_class=PlainTextResponse)def root(): return "Hello, plain text!"This also documents the correct Content-Type in the OpenAPI schema.
HTML Response
Section titled “HTML Response”@app.get("/html")def html_page(): return HTMLResponse(content="<h1>Hello</h1><p>This is HTML</p>")Or using response_class:
@app.get("/html", response_class=HTMLResponse)def html_page(): return "<h1>Hello</h1>"Streaming Response
Section titled “Streaming Response”from starlette.responses import StreamingResponseimport asyncio
async def generate_tokens(): for i in range(10): yield f"data: token_{i}\n\n" await asyncio.sleep(0.1)
@app.get("/stream")def stream(): return StreamingResponse(generate_tokens(), media_type="text/event-stream")Redirect
Section titled “Redirect”from starlette.responses 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"}Or using response_class:
@app.get("/old-path", response_class=RedirectResponse, status_code=302)def old_path(): return "/new-path"File Response
Section titled “File Response”from starlette.responses import FileResponse
@app.get("/download")def download(): return FileResponse("report.pdf", filename="report.pdf")JSON Response with Custom Headers
Section titled “JSON Response with Custom Headers”from starlette.responses import JSONResponse
@app.get("/custom")def custom(): return JSONResponse( content={"data": "value"}, headers={"X-Custom": "header-value"}, )Plain Text Response
Section titled “Plain Text Response”@app.get("/text")def text(): return PlainTextResponse("Hello, plain text!")Default Response Class
Section titled “Default Response Class”Set a default response class for all routes:
from starlette.responses import ORJSONResponse
app = JustAPIApp(default_response_class=ORJSONResponse)Custom Response Class
Section titled “Custom Response Class”Create your own response class:
from starlette.responses 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 Class + Status Code
Section titled “Response Class + Status Code”Combine response_class with status_code:
@app.post("/items", response_class=JSONResponse, status_code=201)def create_item(): return {"message": "created"}See Also
Section titled “See Also”- Return a Response Directly — basic response object usage
- Streaming Output — JustAPI-native streaming
- Static Files — serving files