The easiest way to generate a response object is to use one of the nine (9) convenience methods.
Default Content-Type: text/plain; charset=utf-8 Description: Returns plain text
from sanic.response import text
@app.route("/")asyncdefhandler(request):return text("Hi 😎")
Default Content-Type: text/html; charset=utf-8 Description: Returns an HTML document
from sanic.response import html
@app.route("/")asyncdefhandler(request):return html('<!DOCTYPE html><html lang="en"><meta charset="UTF-8"><div>Hi 😎</div>')
Default Content-Type: application/json Description: Returns a JSON document
from sanic.response import json
@app.route("/")asyncdefhandler(request):return json({"foo":"bar"})
By default, Sanic ships with ujson(opens new window) as its JSON encoder of choice. It is super simple to change this if you want.
from orjson import dumps
json({"foo":"bar"}, dumps=dumps)
If ujson is not installed, it will fall back to the standard library json module.
You may additionally declare which implementation to use globally across your application at initialization:
from orjson import dumps
app = Sanic(..., dumps=dumps)
Default Content-Type: N/A Description: Returns a file
from sanic.response importfile@app.route("/")asyncdefhandler(request):returnawaitfile("/path/to/whatever.png")
Sanic will examine the file, and try and guess its mime type and use an appropriate value for the content type. You could be explicit, if you would like: