Skip to main content

Write JSON REST APIs in the Twisted framework

Project description

retwist

Retwist allows convenient creation of RESTful JSON endpoints in Twisted. Features:

  • Routes: Mapping path patterns like r"/hotels/(.*)/info" to Twisted Resources. Instead of using the Twisted getChild() lookup mechanism.
  • Parsing of URL parameters from requests. Parameters are defined in Resource class scope, e.g. type = retwist.EnumParam(["html", "json]).
  • Handles encoding JSON responses, including support for good old JSONP.

You implement JSON endpoints by subclassing retwist.JsonResource, and implementing the json_GET method.

Example

Here's a simple demo page that parses a required ID parameter, and echoes it back in a JSON object. Note how we register a route "/echo".

import retwist, twisted.internet.reactor

class DemoPage(retwist.JsonResource):

    isLeaf = True

    id = retwist.Param(required=True)

    # Use the "name" argument for parameters whose names are reserved Python keywords:
    from_param = retwist.Param(name="from")

    def json_GET(self, request):
        # This method can also return a Deferred
        args = request.url_args
        return {
            "msg": "You passed ID {} and from {}".format(args["id"], args.get("from"))
        }

site = retwist.RouteSite()
site.addRoute(r"/echo", DemoPage())
twisted.internet.reactor.listenTCP(8080, site)
twisted.internet.reactor.run()

See also examples folder.

JSON parameters

Retwist can parse JSON-encoded parameters, and with the [jsonschema] extra installed, perform schema validations on the data.

For example, this resource will parse the data passed for the "config" parameter, and return a 400 client error if it was invalid JSON, or did not comply with the specified schema:

import retwist

class JsonDemoPage(retwist.JsonResource):
 
    config = retwist.JsonParam(schema={"type": "object"})

    def json_GET(self, request):
        # You can assume request.url_args["config"] to be a dictionary here
        # ...

Sentry error reporting

Install retwist with the [sentry] extra, and enable Sentry reporting like so:

import sentry_sdk
sentry_sdk.init(dsn="...", release="...")

from retwist.util.sentry import enable_sentry_reporting
enable_sentry_reporting()

# This is useful to redirect Twisted log messages to Python's logging module:
from retwist.util.logs import redirect_twisted_logging
redirect_twisted_logging()

This will capture any errors logged to Twisted's logging system and forward exceptions to Sentry. Starting from retwist 0.3, this reports the request URL, headers and data to Sentry.

Development Notes

Retwist comes with a tox configuration to run its test suite on all supported Python versions, as well as a linting and type checking step.

It's possible to install all required Python versions locally via pyenv. Alternatively, use the kiwicom/tox Docker image to run the test suite:

docker pull kiwicom/tox

docker container run \
    --mount src=$PWD,target=/retwist,type=bind \
    --interactive --tty --rm \
    --dns 8.8.8.8 \  # Prevents a DNS issue which occurs on some Linux hosts. This is a Google DNS server, but any other would work too
    kiwicom/tox \
    /bin/bash -c "cd /retwist && find -name '*.pyc' -delete && tox"  # Delete stale *.pyc files to avoid errors on Python 2

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

retwist-0.4.2.tar.gz (14.3 kB view details)

Uploaded Source

File details

Details for the file retwist-0.4.2.tar.gz.

File metadata

  • Download URL: retwist-0.4.2.tar.gz
  • Upload date:
  • Size: 14.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.55.1 CPython/3.7.9

File hashes

Hashes for retwist-0.4.2.tar.gz
Algorithm Hash digest
SHA256 68bdf39e63b16817dc8a358537f4f15da26e34601dbf8cb44835e694e934daee
MD5 3da69928b0c5a683e1962b4cf27b396e
BLAKE2b-256 8025c7a0d9a70287740597ab523fab1d13f3d59965b30002276b03fcd8632888

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page