Saturday, December 28, 2024
Google search engine
HomeLanguagesPython Falcon – Routing

Python Falcon – Routing

Falcon is Python based a lightweight and high-performance Python-based web framework designed for building fast and efficient APIs. There are also other Python-based frameworks for building APIs such as Flask, FastAPI, etc. Routing is a fundamental concept in Falcon, as it determines how incoming HTTP requests are mapped to specific functions or resources in our application. In this article, I described the concept of routing in Python Falcon and how it’s implemented.

What are URI Templates?

Falcon uses URI templates to define routes. These templates specify the structure of URLs and can include placeholders for dynamic values. For example, “/users/{user_id}” is a URI template where {user_id} is a placeholder. placeholder are simple variable that we pass in the URL so we get that particular info. eg. if we want to retrieve details about the user with user_id = 100 then we call “/users/100”.

What are Resource Classes?

Falcon organizes our API into resource classes. Each resource class is responsible for handling specific HTTP methods that can perform CRUD operations(GET, POST, PUT, DELETE, etc.) on a particular URI pattern. we define these resource classes to create our API in Falcon. In Falcon there is request (req) and response(resp) objects that make it easy to handle incoming requests and construct responses.

What is Routing and Mapping?

Falcon maps the incoming clients requests to the appropriate resource class (which we had defined during API development) and method based on the URI pattern and HTTP method. This mapping is typically done in the application’s add_route method.

Let’s understand how routing works in Falcon by example.

Setting up the Project

Before starting coding part we need to install some library we need such as falcon and wsgiref (for creating server to test our API)

pip install falcon
pip install wsgiref

Importing Falcon and Creating an API Object

First of create one main.py file, we will write all our code in the same file. To start using Falcon, we need to import it and create an instance of the falcon.API() class, which represents our application.

Python3




import falcon
app = falcon.API()


Defining Resources

In Falcon, resources are Python classes that handle specific routes or URLs. These resources should inherit from falcon.Resource. we define routes and HTTP methods for these resources using decorators.

Python3




class UserResource:
    def on_get(self, req, resp, user_id):
        resp.status = falcon.HTTP_200
        resp.text = f"Retrieved user with ID {user_id}"
userResource = UserResource()


Adding Resources to the API and URL Parameters

In this step we add our resource(s) to the Falcon API using the add_route() method, which specifies the URL path and the resource class. Falcon also allows us to capture URL parameters from the request. we can define them in the route using curly braces and access them within your resource handler

Python3




app.add_route('/users/{user_id}', userResource)


Creating the server and running the code

As already mentioned we use wsgiref form creating server to actually test our API and see output.

Python3




from wsgiref import simple_server
 
if __name__ == '__main__':
    httpd = simple_server.make_server('127.0.0.1', 8000, app)
    print("Serving Falcon app on http://127.0.0.1:8000")
    httpd.serve_forever()


Example 1: So after all this step our final code should be look like below.

Python3




import falcon
from wsgiref import simple_server
class UserResource:
    def on_get(self, req, resp, user_id):
        resp.status = falcon.HTTP_200
        resp.text = f"Retrieved user with ID {user_id}"
app = falcon.App()
userResource = UserResource()
app.add_route('/users/{user_id}', userResource)
if __name__ == '__main__':
    httpd = simple_server.make_server('127.0.0.1', 8000, app)
    print("Serving Falcon app on http://127.0.0.1:8000")
    httpd.serve_forever()


We can run this code as simple python file we run.

Output:

New-InPrivate-tab---[InPrivate]---Microsoft_-Edge-2023-09-30-13-27-30

Output of falcon routing

Example 2: In this example we create routing such that if user directly click on link “/” then “Hello, GFG User” will returned or if user hit on “/greet/{name}” then we return greet message “Hello, {name}! Welcome to GFG”.

Python3




import falcon
from wsgiref import simple_server
class HelloResource:
    def on_get(self, req, resp):
        resp.text = 'Hello, GFG User'
class GreetResource:
    def on_get(self, req, resp, name):
        resp.text = f'Hello, {name}! Welcome to GFG'
app = falcon.App()
hello = HelloResource()
greet = GreetResource()
app.add_route('/', hello)
app.add_route('/greet/{name}', greet)
if __name__ == '__main__':
    httpd = simple_server.make_server('127.0.0.1', 8000, app)
    print("Serving Falcon app on http://127.0.0.1:8000")
    httpd.serve_forever()


Output:

New-InPrivate-tab---[InPrivate]---Microsoft_-Edge-2023-09-30-13-35-15

greet using falcon routing

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments