Open In App

Build APIs with Falcon in Python

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the sector of web development, building a sturdy and green API is vital. APIs (Application Programming Interfaces) act as a bridge between software program structures, allowing for easy verbal exchange and record change. Python, with its flexibility and flexibility, is a popular choice for growing APIs. Among the numerous Python frameworks to be had for this purpose, Falcon stands proud as an excessive-performance, highly easy framework explicitly designed to construct fast and responsive APIs In this newsletter we are able to explore Falcon, its fundamental ideas, and the steps had to create APIs, with a few illustrative examples.

What is Falcon?

Falcon is a web framework for Python that focuses on imparting an extremely lightweight, excessive-overall performance platform for constructing APIs. It’s not a full-stack framework like Django or Flask, however a special device designed to do one component notably well: deal with API requests and responses effectively Falcon’s major goal is pace, which makes it a pinnacle preference for constructing APIs in which performance and scalability are paramount.

Falcon’s layout philosophy revolves around minimalism and simplicity. It has a small codebase and an easy API, making it clean to analyze and use. The framework is designed for developers who need to build APIs quickly and have first-rate-grained manipulation over the functionality.

Concepts related to Falcon

Before we dive into building APIs with Falcon, permit’s familiarize ourselves with some important standards and additives of the framework:

  1. Resource Handlers
    • In Falcon, a useful aid handler is a Python class that defines how a specific endpoint (URL) needs to reply to incoming HTTP requests.
    • This training is usually inherited from Falcon. Resource and put in force various strategies to deal with specific HTTP techniques like GET, POST, PUT, DELETE, and many others.
    • Resource handlers are at the coronary heart of Falcon’s design, permitting you to shape your API’s true judgment in an easy and organized manner.
  2. Request and Response Objects
    • Falcon affords request and reaction devices that encapsulate incoming HTTP requests and outgoing HTTP responses.
    • These gadgets offer a handy manner to get admission to request data and collect responses.
    • You can use them internal your useful resource handlers to engage with the customer and server.
  3. Routing
    • Routing in Falcon maps incoming HTTP requests to precise useful resource handlers.
    • Falcon offers a simple and intuitive manner to outline routes the usage of the falcon.App elegance.
    • You can specify routes thru attaching aid handlers to specific URL patterns, making it easy to arrange your API’s endpoints.
  4. Middleware
    • Middleware is a powerful idea in Falcon that lets in you to carry out pre-processing and submit-processing tasks on requests and responses.
    • You can use middleware to characteristic authentication, logging, or any other capability that desires to be finished in the course of multiple API endpoints.
  5. Request Parsing and Validation
    • Falcon offers gadget for parsing and validating incoming request information, inclusive of question parameters, request headers, and request bodies.
    • This makes it easier to ensure that your API receives valid and properly formatted input.

Steps needed to Build APIs with Falcon

Now that we have a stable expertise of Falcon’s center principles, allow’s walk via the stairs required to construct APIs using Falcon:

1. Installation

First, you need to put in Falcon. You can do that the usage of pip, the Python bundle manager

pip install falcon

2. Create a Falcon Application

The basis of any Falcon-based totally API is the falcon.App item. You create an example of this elegance to outline your API, set up routing, and configure middleware.

Python3




import falcon
 
app = falcon.App(middleware=[
    # Add your middleware here
])


3. Define Resource Handlers

Next, you define aid handlers as Python instructions. These instructions inherit from falcon.Resource and put in force methods similar to the HTTP methods they should take care of (e.G., on_get, on_post, on_put, on_delete).

Python3




class HelloWorldResource:
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.text = 'Hello, World!'


4. Map URLs to Resource Handlers

You map URLs in your useful resource handlers through adding them for your Falcon app’s router. This is accomplished the usage of the add_route technique of the falcon.App instance.

Python3




app.add_route('/hello', HelloWorldResource())


5. Run the Falcon Application

Finally, you run your Falcon software using a web server of your desire. Falcon is WSGI-compliant, which means you may use various WSGI servers like Gunicorn or uWSGI to serve your API.

Python3




if __name__ == '__main__':
    from wsgiref import simple_server
 
    httpd = simple_server.make_server('localhost', 8000, app)
    httpd.serve_forever()


And that’s it! You’ve created a basic Falcon API. You can now make HTTP requests to the defined endpoints and acquire responses from your resource handlers.

Building a To-Do List API

In this situation, we have created a TodoResource that handles GET and POST requests to manipulate a listing of to-do gadgets. The API allows you to retrieve the listing of todos the use of a GET request and add a new todo item using a POST request.

Python3




import falcon
import json
 
class TodoResource:
    def __init__(self):
        self.todos = []
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.body = json.dumps({'todos': self.todos})
    def on_post(self, req, resp):
        data = req.media
        todo = data.get('todo')
        if todo is not None:
            self.todos.append(todo)
            resp.status = falcon.HTTP_201
            resp.body = json.dumps({'message': 'Todo added successfully'})
        else:
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.body = json.dumps({'error': 'Invalid request'})
 
app = falcon.App()
app.add_route('/todos', TodoResource())
 
if __name__ == '__main__':
    from wsgiref import simple_server
 
    httpd = simple_server.make_server('localhost', 8000, app)
    httpd.serve_forever()


Output

ezgifcom-video-to-gif-(4)

Building a To-Do List API With Authentication

Adding authentication in your API is a not unusual requirement. The Falcon middleware function makes authentication clean to apply. Here is an instance of the usage of Falcon’s built-in falcon.Auth middleware. For this example, you may need to install falcon_auth package. Use the following command to install the falcon_auth package using pip.

pip install falcon_auth

In this example, we use the Falcon falcon-auth middleware to feature preliminary authentication to unique techniques. ProtectedResource requires authentication, PublicResource does now not. You can customize the authentication good judgment to in shape the desires of your application.

Python3




import falcon
from falcon_auth import FalconAuthMiddleware, BasicAuthBackend
auth_backend = BasicAuthBackend(lambda username, password: username == 'user' and password == 'password')
app = falcon.App(middleware=[
    FalconAuthMiddleware(auth_backend, exempt_routes=['/public']),
])
class ProtectedResource:
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.text = 'Authenticated resource'
class PublicResource:
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.text = 'Public resource'
 
app.add_route('/protected', ProtectedResource())
app.add_route('/public', PublicResource())
 
if __name__ == '__main__':
    from wsgiref import simple_server
    httpd = simple_server.make_server('localhost', 8000, app)
    httpd.serve_forever()


Output

ezgifcom-video-to-gif-(5)

Conclusion

Falcon is a effective subprogram for building high-overall performance APIs in Python. Its compact design and attention on speed make it an super choice for programs that require speedy and green API endpoints. By expertise the fundamental concepts of Falcon, following the stairs to create an API with Falcon, and exploring realistic examples, you may use this framework to create a strong and green API that meets your wishes particularly deal with whether to build a simple To-Do List API or enforce a complex authentication mechanism , Falcon gives the power and functionality you need in your internet API projects.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads