Skip to content

Responses

Starlette contains response classes for sending appropriate ASGI messages over the send channel.

response

Signed by: Response(content, status_code=200, headers=None, media_type=None)

  • content - A string or byte string.
  • status_code - An integer HTTP status code.
  • headers - String dictionary.
  • media_type - A string that gives the media type. For example: "text/html"

Starlette will automatically contain a Content-Length header. It will also contain a Content-Type header based on media_type and append a character set for the text type unless the character set has been specified in media_type.

Once you instantiate a response, you can send it by invoking it as an ASGI application instance.

from starlette.responses import Response


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = Response('Hello, world!', media_type='text/plain')
    await response(scope, receive, send)

set cookies

Starlette provided a way set_cookie Method that allows you to set cookies on the response object.

Signed by: Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax")

  • key - A string that will serve as a Cookie key.
  • value - A string to be used as the Cookie value.
  • max_age-An integer that defines the lifetime of cookies in seconds. A negative integer or a value of 0 will immediately discard cookies.Optional
  • expires - Either an integer defining the number of seconds before the Cookie expires, or a datetime. Optional
  • path - A string specifying the subset of routes to which this Cookie will apply. Optional
  • domain - A string specifying the domain in which cookies are valid. Optional
  • secure - A Boolean value indicating that cookies will be sent to the server only when a request is made using the SSL and HTTPS protocols. Optional
  • httponly - A Boolean value representing the value of the Document.cookie attribute, XMLHttpRequest or Request API, this Cookie cannot be accessed via JavaScript. Optional
  • samesite - A string specifying the sameSite policy for cookies. Valid values are 'lax' 、 'strict' sum 'none' . Default is 'lax' 。 Optional

delete cookies

Instead, Starlette also provides an delete_cookie method to manually expire cookies.

Signed by: Response.delete_cookie(key, path='/', domain=None)

HTML response

Takes some text or bytes and returns an HTML response.

from starlette.responses import HTMLResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = HTMLResponse('<html><body><h1>Hello, world!</h1></body></html>')
    await response(scope, receive, send)

plain text response

Takes some text or bytes and returns a plain text response.

from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

JSON response

Get some data and return an application/json encoded response.

from starlette.responses import JSONResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = JSONResponse({'hello': 'world'})
    await response(scope, receive, send)

Custom JSON Serialization

If you need fine-grained control over JSON serialization, you can subclass JSONResponse and override the render method.

For example, if you want to use a third-party JSON library such as orjson:

from typing import Any

import orjson
from starlette.responses import JSONResponse


class OrjsonResponse(JSONResponse):
    def render(self, content: Any) -> bytes:
        return orjson.dumps(content)

In general, unless you want to micro-optimize specific endpoints or serialize non-standard object types, you might want to stick with JSONResponse by default.

redirect response

Returns an HTTP redirect. The default status code is 307.

from starlette.responses import PlainTextResponse, RedirectResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    if scope['path'] != '/':
        response = RedirectResponse(url='/')
    else:
        response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

streaming response

Accept an asynchronous generator or a regular generator/iterator and stream the response body.

from starlette.responses import StreamingResponse
import asyncio


async def slow_numbers(minimum, maximum):
    yield '<html><body><ul>'
    for number in range(minimum, maximum + 1):
        yield '<li>%d</li>' % number
        await asyncio.sleep(0.5)
    yield '</ul></body></html>'


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    generator = slow_numbers(1, 10)
    response = StreamingResponse(generator, media_type='text/html')
    await response(scope, receive, send)

Note that class file objects, such as those created by open(), are plain iterators. Therefore, you can return them directly in StreamingResponse.

file response

Stream files asynchronously as responses.

Instantiation requires a different set of parameters than other response types:

  • path - The file path of the file to stream.
  • headers - Any custom headers to include as dictionaries.
  • media_type - A string that gives the media type. If not set, the file name or path will be used to infer the media type.
  • filename-If set, it will be included in the response Content-Disposition.
  • content_disposition_type-To be included in the response Content-Disposition. Can be set to Attachment (default) or Inline.

The file response will contain the appropriate Content-Length,Last-Modified, and ETag headers.

from starlette.responses import FileResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = FileResponse('statics/favicon.ico')
    await response(scope, receive, send)

Third Party Response

Event Source Response

A response class that implements the server sending events. It enables event flow from the server to the client without the complexity of WebSockets.

baize.asgi.FileResponse

As a smooth replacement for Starlette FileResponse, it automatically handles Head method and Range requests.