Falcon Hello World

This article explains about, falcon the fastest python framework for REST API's and gives you an introduction with hello world example program.

Hello all.  Today we will see about python falcon framework.

What is falcon?  

    Falcon is a minimalistic python framework and one of the fastest framework of pythons.
If you have to develop HTTP api's or standalone backend system or REST API services, falcon is the best choice. It's light weight and fast .

Benefits:

  • It doesn't have any template engines and ORM.
  • It gives full control to developer to choose what your applications want to do.

When to use?

  • Standalone Backend System
  • Rest API's

Let's get into session

Installation

   pip install falcon==1.0.0 

   Werkzeug==0.10.4

Hope you have falcon installed. Now lets start using falcon

save this as  hello.py


import falcon
from werkzeug.serving import run_simple

app = falcon.API()


class HelloViewAPI:
    """
         This is an endpoint for Hello View
    """
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.content_type = "text/plain"
        resp.body = "Hello World!"


    def on_post(self, req, resp):
        resp.status = falcon.HTTP_201
        resp.content_type = "text/plain"
        resp.body = "Resource added successfully"
    def on_put(self, req, resp):
         """
           your codes goes here for put method
          """
        pass

    def on_delete(self, req, resp):
        """
            your codes goes here for delete method
        """
        pass


hobj = HelloViewAPI()

app.add_route('/hello', hobj)


if __name__ == '__main__':
    run_simple('0.0.0.0', 5000, app, use_reloader=True)

 

run  python hello.py

Open Browser  http://localhost:5000/hello

which responses

  Hello World!

Explanation:

As you see  HelloViewAPI has four methods  GET, POST, PUT, DELETE

if request method is  GET the  on_get(self, req, resp) is called and for POST requests on_post() is getting called .

So we just have to focus on our code and application logic.

To get request params

req.params -> gives url parameters as python dict
  (e.x) /hello?name=bala -> {"name": "bala"}

req.get_param('name')  # gets value of param name
req.get_param_as_list('name') # gets param value as list

To Pass value in url

app.add_route('/hello/{id}', hobj)

In your view on_get(req,resp, id) # id gets the value passed in url

Important: we have to set status code , content_type headers for response.

Middleware Example

class AuthMiddleware(object):

def process_request(self, req, resp):
token = req.get_header('Authorization')
account_id = req.get_header('Account-ID')

challenges = ['Token type="Fernet"']

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

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

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

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

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

app = falcon.API(middleware=AuthMiddleware())


Hope this helps .Thanks for reading .

Happy coding !

Leave a comment

(Note: Comments are moderated)