📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials API Design Content Negotiation

Content Negotiation

4 min read
Use Accept and Content-Type headers to negotiate JSON, CSV, and XML formats between client and server.

Content Negotiation

# Client requests format
Accept: application/json
Accept: text/csv

# FastAPI multi-format
import csv, io
from fastapi.responses import StreamingResponse

@app.get("/export")
def export(format: str = "json"):
    if format == "csv":
        output = io.StringIO()
        writer = csv.DictWriter(output, fieldnames=["id","name"])
        writer.writeheader()
        writer.writerows(get_data())
        return StreamingResponse(
            io.BytesIO(output.getvalue().encode()),
            media_type="text/csv",
            headers={"Content-Disposition":"attachment; filename=data.csv"}
        )
    return get_data()