Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Falcon Falcon web framework docs Build Status codecov.io

Perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away.

- Antoine de Saint-Exupéry

Falcon is a high-performance Python framework for building cloud APIs. It encourages the REST architectural style, and tries to do as little as possible while remaining highly effective.

Design Goals

Fast. Cloud APIs need to turn around requests quickly, and make efficient use of hardware. This is particularly important when serving many concurrent requests. Falcon is among the fastest WSGI frameworks available, processing requests several times faster than other Python web frameworks.

Light. Only the essentials are included, with six and mimeparse being the only dependencies outside the standard library. We work hard to keep the code lean, making Falcon easier to test, secure, optimize, and deploy.

Flexible. Falcon is not opinionated when it comes to talking to databases, rendering content, authorizing requests, etc. You are free to mix and match your own favorite libraries. Falcon apps work with any WSGI server, and run great under CPython 2.6-2.7, PyPy, Jython 2.7, and CPython 3.3-3.5.

Features

  • Highly-optimized, extensible code base

  • Intuitive routing via URI templates and REST-inspired resource classes

  • Easy access to headers and bodies through request and response classes

  • DRY request processing via middleware components and hooks

  • Idiomatic HTTP error responses

  • Straightforward exception handling

  • Snappy unit testing through WSGI helpers and mocks

  • CPython 2.6-2.7, PyPy, Jython 2.7, and CPython 3.3-3.5 support

  • ~20% speed boost when Cython is available

Install

PyPy

PyPy is the fastest way to run your Falcon app. However, note that only the PyPy 2.7 compatible release is currently supported.

$ pip install falcon

CPython

Falcon also fully supports CPython 2.6, 2.7, 3.3, 3.4, and 3.5. Under CPython, Falcon will compile itself with Cython, if available, for an extra speed boost. The following will make sure Cython is installed first, and that you always have the latest and greatest.

$ pip install --upgrade cython falcon

Installing on OS X

Xcode Command Line Tools are required to compile Cython. Install them with this command:

$ xcode-select --install

The Xcode 5.1 CLang compiler treats unrecognized command-line options as errors; this can cause problems under Python 2.6, for example:

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

You can work around errors caused by unused arguments by setting some environment variables:

$ export CFLAGS=-Qunused-arguments
$ export CPPFLAGS=-Qunused-arguments
$ pip install cython falcon

Test

$ pip install -r tools/test-requires
$ pip install nose && nosetests

To run the default set of tests:

$ pip install tox && tox

Read the docs

The docstrings in the Falcon code base are quite extensive, and we recommend keeping a REPL running while learning the framework so that you can query the various modules and classes as you have questions.

Online docs are available at: http://falcon.readthedocs.org

You can build the same docs locally as follows:

$ pip install -r tools/doc-requires
$ cd doc
$ make html

$ # open _build/html/index.html

Getting started

Here is a simple, contrived example showing how to create a Falcon-based API.

# things.py

# Let's get this party started
import falcon


# Falcon follows the REST architectural style, meaning (among
# other things) that you think in terms of resources and state
# transitions, which map to HTTP verbs.
class ThingsResource:
    def on_get(self, req, resp):
        """Handles GET requests"""
        resp.status = falcon.HTTP_200  # This is the default status
        resp.body = ('\nTwo things awe me most, the starry sky '
                     'above me and the moral law within me.\n'
                     '\n'
                     '    ~ Immanuel Kant\n\n')

# falcon.API instances are callable WSGI apps
app = falcon.API()

# Resources are represented by long-lived class instances
things = ThingsResource()

# things will handle all requests to the '/things' URL path
app.add_route('/things', things)

You can run the above example using any WSGI server, such as uWSGI or Gunicorn. For example:

$ pip install gunicorn
$ gunicorn things:app

Then, in another terminal:

$ curl localhost:8000/things

A more complex example

Here is a more involved example that demonstrates reading headers and query parameters, handling errors, and working with request and response bodies.

import json
import logging
import uuid
from wsgiref import simple_server

import falcon
import requests


class StorageEngine(object):

    def get_things(self, marker, limit):
        return [{'id': str(uuid.uuid4()), 'color': 'green'}]

    def add_thing(self, thing):
        thing['id'] = str(uuid.uuid4())
        return thing


class StorageError(Exception):

    @staticmethod
    def handle(ex, req, resp, params):
        description = ('Sorry, couldn\'t write your thing to the '
                       'database. It worked on my box.')

        raise falcon.HTTPError(falcon.HTTP_725,
                               'Database Error',
                               description)


class SinkAdapter(object):

    engines = {
        'ddg': 'https://duckduckgo.com',
        'y': 'https://search.yahoo.com/search',
    }

    def __call__(self, req, resp, engine):
        url = self.engines[engine]
        params = {'q': req.get_param('q', True)}
        result = requests.get(url, params=params)

        resp.status = str(result.status_code) + ' ' + result.reason
        resp.content_type = result.headers['content-type']
        resp.body = result.text


class AuthMiddleware(object):

    def process_request(self, req, resp):
        token = req.get_header('X-Auth-Token')
        project = req.get_header('X-Project-ID')

        if token is None:
            description = ('Please provide an auth token '
                           'as part of the request.')

            raise falcon.HTTPUnauthorized('Auth token required',
                                          description,
                                          href='http://docs.example.com/auth')

        if not self._token_is_valid(token, project):
            description = ('The provided auth token is not valid. '
                           'Please request a new token and try again.')

            raise falcon.HTTPUnauthorized('Authentication required',
                                          description,
                                          href='http://docs.example.com/auth',
                                          scheme='Token; UUID')

    def _token_is_valid(self, token, project):
        return True  # Suuuuuure it's valid...


class RequireJSON(object):

    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')

        if req.method in ('POST', 'PUT'):
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',
                    href='http://docs.examples.com/api/json')


class JSONTranslator(object):

    def process_request(self, req, resp):
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333
        if req.content_length in (None, 0):
            # Nothing to do
            return

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                                        'A valid JSON document is required.')

        try:
            req.context['doc'] = json.loads(body.decode('utf-8'))

        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect or not encoded as '
                                   'UTF-8.')

    def process_response(self, req, resp, resource):
        if 'result' not in req.context:
            return

        resp.body = json.dumps(req.context['result'])


def max_body(limit):

    def hook(req, resp, resource, params):
        length = req.content_length
        if length is not None and length > limit:
            msg = ('The size of the request is too large. The body must not '
                   'exceed ' + str(limit) + ' bytes in length.')

            raise falcon.HTTPRequestEntityTooLarge(
                'Request body is too large', msg)

    return hook


class ThingsResource:

    def __init__(self, db):
        self.db = db
        self.logger = logging.getLogger('thingsapp.' + __name__)

    def on_get(self, req, resp, user_id):
        marker = req.get_param('marker') or ''
        limit = req.get_param_as_int('limit') or 50

        try:
            result = self.db.get_things(marker, limit)
        except Exception as ex:
            self.logger.error(ex)

            description = ('Aliens have attacked our base! We will '
                           'be back as soon as we fight them off. '
                           'We appreciate your patience.')

            raise falcon.HTTPServiceUnavailable(
                'Service Outage',
                description,
                30)

        # An alternative way of doing DRY serialization would be to
        # create a custom class that inherits from falcon.Request. This
        # class could, for example, have an additional 'doc' property
        # that would serialize to JSON under the covers.
        req.context['result'] = result

        resp.set_header('X-Powered-By', 'Small Furry Creatures')
        resp.status = falcon.HTTP_200

    @falcon.before(max_body(64 * 1024))
    def on_post(self, req, resp, user_id):
        try:
            doc = req.context['doc']
        except KeyError:
            raise falcon.HTTPBadRequest(
                'Missing thing',
                'A thing must be submitted in the request body.')

        proper_thing = self.db.add_thing(doc)

        resp.status = falcon.HTTP_201
        resp.location = '/%s/things/%s' % (user_id, proper_thing['id'])


# Configure your WSGI server to load "things.app" (app is a WSGI callable)
app = falcon.API(middleware=[
    AuthMiddleware(),
    RequireJSON(),
    JSONTranslator(),
])

db = StorageEngine()
things = ThingsResource(db)
app.add_route('/{user_id}/things', things)

# If a responder ever raised an instance of StorageError, pass control to
# the given handler.
app.add_error_handler(StorageError, StorageError.handle)

# Proxy some things to another service; this example shows how you might
# send parts of an API off to a legacy system that hasn't been upgraded
# yet, or perhaps is a single cluster that all data centers have to share.
sink = SinkAdapter()
app.add_sink(sink, r'/search/(?P<engine>ddg|y)\Z')

# Useful for debugging problems in your API; works with pdb.set_trace()
if __name__ == '__main__':
    httpd = simple_server.make_server('127.0.0.1', 8000, app)
    httpd.serve_forever()

Community

The Falcon community maintains a mailing list that you can use to share your ideas and ask questions about the framework. We use the appropriately minimalistic Librelist to host the discussions.

To join the mailing list, simply send your first email to falcon@librelist.com! This will automatically subscribe you to the mailing list and sends your email along to the rest of the subscribers. For more information about managing your subscription, check out the Librelist help page.

We expect everyone who participates on the mailing list to act professionally, and lead by example in encouraging constructive discussions. Each individual in the community is responsible for creating a positive, constructive, and productive culture. See also the Falcon Code of Conduct

Discussions are archived for posterity.

We also hang out in #falconframework on freenode, where everyone is always welcome to ask questions and share ideas.

Contributing

Kurt Griffiths (kgriffs) is the creator and current maintainer of the Falcon framework, with the generous help of a number of stylish and talented contributors.

Pull requests are always welcome. We use the GitHub issue tracker to organize our work, put you do not need to open a new issue before submitting a PR.

Before submitting a pull request, please ensure you have added/updated the appropriate tests (and that all existing tests still pass with your changes), and that your coding style follows PEP 8 and doesn’t cause pyflakes to complain.

Commit messages should be formatted using AngularJS conventions.

Comments follow Google’s style guide, with the additional requirement of prefixing inline comments using your GitHub nick and an appropriate prefix:

  • TODO(riker): Damage report!

  • NOTE(riker): Well, that’s certainly good to know.

  • PERF(riker): Travel time to the nearest starbase?

  • APPSEC(riker): In all trust, there is the possibility for betrayal.

See also: CONTRIBUTING.md

Metadata

Release files for falcon 1.0.0rc1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distributions (sdists)

Source distribution for falcon 1.0.0rc1
File Size Uploaded Provenance Actions
falcon-1.0.0rc1.zip 372.6 kB Without provenance Details for falcon-1.0.0rc1.zip
falcon-1.0.0rc1.tar.gz 305.1 kB Without provenance Details for falcon-1.0.0rc1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for falcon 1.0.0rc1
File Actions
falcon-1.0.0rc1-cp35-cp35m-macosx_10_11_x86_64.whl CPython 3.5 CPython 3.5 pymalloc macOS 10.11+ x86-64 Details for falcon-1.0.0rc1-cp35-cp35m-macosx_10_11_x86_64.whl
falcon-1.0.0rc1-cp34-cp34m-macosx_10_11_x86_64.whl CPython 3.4 CPython 3.4 pymalloc macOS 10.11+ x86-64 Details for falcon-1.0.0rc1-cp34-cp34m-macosx_10_11_x86_64.whl
falcon-1.0.0rc1-cp33-cp33m-macosx_10_10_x86_64.whl CPython 3.3 CPython 3.3 pymalloc macOS 10.10+ x86-64 Details for falcon-1.0.0rc1-cp33-cp33m-macosx_10_10_x86_64.whl
falcon-1.0.0rc1-cp27-cp27m-macosx_10_11_x86_64.whl CPython 2.7 CPython 2.7 pymalloc macOS 10.11+ x86-64 Details for falcon-1.0.0rc1-cp27-cp27m-macosx_10_11_x86_64.whl

Total release size: 3.6 MB

Release files / falcon-1.0.0rc1.zip

Download URL falcon-1.0.0rc1.zip
Size 372.6 kB
Tags Source
SHA-256 checksum
How to use checksums
49c23d6d6d71a116b29fde1d36c8ba3a730ec13b4252641234ea47f83871d3b2
BLAKE2b-256 checksum
How to use checksums
bf78e4dd0db87c5c1ada38c04c2fc5a3cc3d8f98b461753e2272c85478e15972
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / falcon-1.0.0rc1.tar.gz

Download URL falcon-1.0.0rc1.tar.gz
Size 305.1 kB
Tags Source
SHA-256 checksum
How to use checksums
989afcb34aa12f6a053a5f53490363e91dc8487441ae8b0b3425349036a032e3
BLAKE2b-256 checksum
How to use checksums
267370ca7b6e30112d608ff599448345fb69b3bdfb438f96d2442d0eb60b3df9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / falcon-1.0.0rc1-cp35-cp35m-macosx_10_11_x86_64.whl

Download URL falcon-1.0.0rc1-cp35-cp35m-macosx_10_11_x86_64.whl
Size 735.8 kB
Tags CPython 3.5 CPython 3.5 pymalloc macOS 10.11+ x86-64
SHA-256 checksum
How to use checksums
c25ea05b6a11794f9227c87167bb6bf4b33e05f56ca27222cb806e482134053b
BLAKE2b-256 checksum
How to use checksums
7a318ad29a7cee68020d0f9ee5587a2f9d048c2f9e1582101cdd8d052bbffa03
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / falcon-1.0.0rc1-cp34-cp34m-macosx_10_11_x86_64.whl

Download URL falcon-1.0.0rc1-cp34-cp34m-macosx_10_11_x86_64.whl
Size 741.2 kB
Tags CPython 3.4 CPython 3.4 pymalloc macOS 10.11+ x86-64
SHA-256 checksum
How to use checksums
c751ae2dfe1a7c5fa585b76c20fcefe68cab17bf20d5c05ce8d0606a89ae4eb0
BLAKE2b-256 checksum
How to use checksums
0512fe926c12f07e3dbc058c59f5ebd9652ea8db4ddb0a6d4bb8465acd18f7b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / falcon-1.0.0rc1-cp33-cp33m-macosx_10_10_x86_64.whl

Download URL falcon-1.0.0rc1-cp33-cp33m-macosx_10_10_x86_64.whl
Size 740.1 kB
Tags CPython 3.3 CPython 3.3 pymalloc macOS 10.10+ x86-64
SHA-256 checksum
How to use checksums
12f1fd565d23fc64300d669253e48b97163465264e03f91c1b985861230ebeea
BLAKE2b-256 checksum
How to use checksums
12288ee4d557f716c55fb1390b1fc42177f03b98d8299e8253032fdd7eb1097e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / falcon-1.0.0rc1-cp27-cp27m-macosx_10_11_x86_64.whl

Download URL falcon-1.0.0rc1-cp27-cp27m-macosx_10_11_x86_64.whl
Size 738.7 kB
Tags CPython 2.7 CPython 2.7 pymalloc macOS 10.11+ x86-64
SHA-256 checksum
How to use checksums
62d8ca15da6e1bc92ad35782fb76393c21363f9fce2a07cd4a100e470ce57c3a
BLAKE2b-256 checksum
How to use checksums
8b24ba01bddf2dfa455a622a8a0890ffbb0eb7e31e0d52679adc0a9d885c6869
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for falcon 1.0.0rc1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page