0Pricing
FastAPI Backend Development Bootcamp · Lesson

Headers, Cookies, and Custom Responses

Read request headers and cookies, set them on responses, and return custom response types like plain text, HTML, redirects, and streaming in FastAPI.

Headers, Cookies, and Custom Responses is a free FastAPI Backend Development Bootcamp lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the FastAPI Backend Development Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Beyond the JSON Body

Request and response handling involves more than the JSON body. Headers and cookies carry metadata like auth tokens, content negotiation, and sessions. FastAPI gives you typed access to both.

Reading a Header

Declare a parameter with Header to read an incoming header. FastAPI auto-converts user_agent to the User-Agent header name.

from fastapi import FastAPI, Header

app = FastAPI()

@app.get('/info')
async def info(user_agent: str = Header(default=None)):
    return {'ua': user_agent}

Reading Cookies

Use Cookie to read a named cookie, just like headers and query params.

from fastapi import Cookie

@app.get('/session')
async def session(session_id: str = Cookie(default=None)):
    return {'session': session_id}

Setting Headers on a Response

Inject a Response object to set headers while still returning normal data.

from fastapi import Response

@app.get('/items')
async def items(response: Response):
    response.headers['X-Total-Count'] = '42'
    return ['a', 'b']

Setting Cookies

Call response.set_cookie to send a cookie back to the client. Add flags like httponly and secure for safety.

@app.post('/login')
async def login(response: Response):
    response.set_cookie('session_id', 'abc123', httponly=True, secure=True)
    return {'ok': True}

Plain Text and HTML Responses

Return non-JSON content with specialized response classes.

from fastapi.responses import PlainTextResponse, HTMLResponse

@app.get('/text', response_class=PlainTextResponse)
async def text():
    return 'hello'

@app.get('/page', response_class=HTMLResponse)
async def page():
    return '<h1>Hi</h1>'

Redirects

Send the client elsewhere with RedirectResponse. Choose the status code for permanent vs temporary redirects.

from fastapi.responses import RedirectResponse

@app.get('/old')
async def old():
    return RedirectResponse(url='/new', status_code=301)

Header Name Conversion

FastAPI converts underscores in parameter names to hyphens for headers. This pure example shows the same idea.

def to_header_name(param):
    return '-'.join(w.capitalize() for w in param.split('_'))
print(to_header_name('user_agent'))
print(to_header_name('x_api_key'))

Streaming Responses

For large or generated data, stream it with StreamingResponse so you do not buffer everything in memory.

from fastapi.responses import StreamingResponse

def rows():
    for i in range(3):
        yield f'row {i}\n'

@app.get('/export')
async def export():
    return StreamingResponse(rows(), media_type='text/plain')

Custom Status Codes

Set a default status for an operation with the status_code argument, or override per request via the injected Response.

from fastapi import status

@app.post('/items', status_code=status.HTTP_201_CREATED)
async def create():
    return {'created': True}

Security Notes

When setting auth cookies, prefer httponly=True (blocks JS access), secure=True (HTTPS only), and samesite to mitigate CSRF.

Quick Check

You declare x_api_key: str = Header(). Which incoming HTTP header does FastAPI map this to?

Recap

You handled the full request/response surface:

  • Read headers and cookies with Header and Cookie.
  • Set headers and cookies via the injected Response.
  • Returned plain text, HTML, redirects, and streaming responses.
  • Applied secure cookie flags and custom status codes.

Frequently asked questions

Is the “Headers, Cookies, and Custom Responses” lesson free?

Yes — the full text of “Headers, Cookies, and Custom Responses” is free to read here on the web, and the FastAPI Backend Development Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the FastAPI Backend Development Bootcamp course, upgrade to CoddyKit PRO.

What will I learn in “Headers, Cookies, and Custom Responses”?

Read request headers and cookies, set them on responses, and return custom response types like plain text, HTML, redirects, and streaming in FastAPI. You practise FastAPI Backend Development Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start FastAPI Backend Development Bootcamp?

No prior experience is required. FastAPI Backend Development Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Headers, Cookies, and Custom Responses” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this FastAPI Backend Development Bootcamp lesson?

Yes. Every FastAPI Backend Development Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Pydantic Models for Request Body
  2. Response Models & Status Codes
  3. Form Data & File Uploads
  4. Headers, Cookies, and Custom Responses
← Back to FastAPI Backend Development Bootcamp