Responses

There are two types of responses: Primitive and HTTP.

Primitive Responses

When returning a response for a Teletype run command (and sometimes for HTTP) you can return primitive Python types like str, int, float, Decimal, bool, dict, list, and tuple – we will take care of serializing them. If multiple values are returned, they will be converted to a list.

Examples

@app.lib.run()
def run_handler(event): 
    return "Hello, space!"

@app.lib.http("/", methods=['GET'])
def get_handler(event): 
    return {"name": "Wesley", "age": 27}


HTTP Responses

In addition to returning Primitive responses, the DETA Library provides helper classes for returning HTTP-specific responses. These include Response (which you can customize), JSON, HTML, and Redirect.

To use any of these responses, first import them from deta.lib.responses:

from deta.lib.responses import <module>


Response

This is the base response and can be used to return custom responses.

Response(content, content_type="text/plain", code=200, headers=None)

Arguments

  • content: any JSON-serializable value.
    • this field is required.
  • content_type: str – HTTP "Content-Type" header.
    • Optional, defaults to "text/plain".
  • code: int – HTTP response status code (external link).
    • Optional, defaults to 200.
  • headers: dict – a key-value pairs of response HTTP headers and their values.
    • Optional, defaults to {"Content-Type": "text/plain"}

Example

from deta.lib.responses import Response

@app.lib.http("/", methods=['GET'])
def get_handler(event): 
    return Response("A GET triggered me!", content_type="text/plain", code=200, headers=None)


JSON

Inherits from Response.

JSON(content, content_type="application/json", code=200, headers=None)

Example

from deta.lib.responses import JSON


@app.lib.http("/", methods=['GET'])
def get_handler(event): 
    response = {"name": "Wesley", "age": 27}
    return JSON(response)

@app.lib.http("/users", methods=['POST'])
def post_handler(event): 
    # parse and save user's data...
    response = {"status": "ok"}
    return JSON(response, code=201)


HTML

Inherits from Response.

HTML(content, content_type="text/html", code=None, headers=None)

Example

from deta.lib.responses import HTML


@app.lib.http("/", methods=['GET'])
def get_handler(event): 
    # it is also possible to return an SVG object the same way 
    return HTML('<h1>hello world</h1>')


Redirect

For HTTP redirects.

Redirect(location, temp=False)

Arguments

  • location: required, str – the target URL.
    • Example: "https://deta.sh/"
  • temp: bool
    • False for permanent HTTP redirect (code 301, default)
    • Truefor temporary redirect (code 302).

Example

from deta.lib.responses import Redirect


@app.lib.http("/", methods=['GET'])
def get_handler(event): 
    return Redirect("https://example.com/new-page", temp=True)