Open In App

Python Falcon - SQLAlchemy Models

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python Falcon is an up-to-date web framework with an adjustable applicative architecture that is oriented to creating high-speed application processes and APIs. Another often implemented pattern is CRUD and interaction with the database can be facilitated with the help of SQLAlchemy for Python. When used with SQLAlchemy, Falcon provides developers with the tools to build great web applications using relations databases as backends that are optimized, easy to maintain, and scalable.

Setting Up the Environment

First of all, it is necessary to install both Falcon and SQLAlchemy as they will be the core libraries used in the following model. You can do this using pip:

pip install falcon sqlalchemy

Creating a Falcon Application with SQLAlchemy

If you are implementing the API, the next step after completing the creation of the Falcon application is creating a Falcon application with SQLAlchemy.

To further demonstrate how Falcon works withe h SQLAlchemy, let’s create a rather stripped-down API for managing users. It will be designed to perform four operations namely, create, read, update, and delete with respect to users.

Step 1: Introduction to SQLAlchemy and define the SQLAlchemy Models

Firstly, it is necessary to define our models based on the SQLAlchemy toolkit. The final step is to create a file with the name ‘models. py':

Python
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    email = Column(String, nullable=False, unique=True)

# SQLite database URL for demonstration purposes
DATABASE_URL = "sqlite:///users.db"

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Create the database tables
Base.metadata.create_all(bind=engine)

This code defines a User model with three fields: id, name, and email. It also sets up an SQLite database and a session maker for interacting with the database.

Step 2: Creating Falcon Resources

Next, create a file named resources.py where we define our Falcon resources. These resources will manage the HTTP requests and also the communication with the SQLAlchemy models.

Python
import falcon
from sqlalchemy.orm import Session
from models import User, SessionLocal

class UserResource:
    def on_get(self, req, resp, user_id):
        session: Session = SessionLocal()
        user = session.query(User).filter(User.id == user_id).first()
        if user:
            resp.media = {'id': user.id, 'name': user.name, 'email': user.email}
        else:
            resp.status = falcon.HTTP_404
            resp.media = {'error': 'User not found'}
        session.close()

    def on_post(self, req, resp):
        session: Session = SessionLocal()
        data = req.media
        user = User(name=data['name'], email=data['email'])
        session.add(user)
        session.commit()
        resp.media = {'id': user.id, 'name': user.name, 'email': user.email}
        session.close()

    def on_put(self, req, resp, user_id):
        session: Session = SessionLocal()
        data = req.media
        user = session.query(User).filter(User.id == user_id).first()
        if user:
            user.name = data['name']
            user.email = data['email']
            session.commit()
            resp.media = {'id': user.id, 'name': user.name, 'email': user.email}
        else:
            resp.status = falcon.HTTP_404
            resp.media = {'error': 'User not found'}
        session.close()

    def on_delete(self, req, resp, user_id):
        session: Session = SessionLocal()
        user = session.query(User).filter(User.id == user_id).first()
        if user:
            session.delete(user)
            session.commit()
            resp.media = {'message': 'User deleted'}
        else:
            resp.status = falcon.HTTP_404
            resp.media = {'error': 'User not found'}
        session.close()

This particular resource class contains methods for handling the HTTP methods GET, POST, PUT and DELETE. Both methods use SQLAlchemy sessions to query the database for CRUD operations.

Step 3: Setting Up the Falcon Application

Now, create a file named app.py to set up the Falcon application and add routes for the user resource.

Python
import falcon
from resources import UserResource

# Create the Falcon application
app = falcon.App()

# Instantiate the user resource
user_resource = UserResource()

# Add routes
app.add_route('/users/{user_id:int}', user_resource)
app.add_route('/users', user_resource)

Step 4: Running the Application

Create a file named server.py to run the Falcon application:

Python
from wsgiref import simple_server
import app

if __name__ == '__main__':
    httpd = simple_server.make_server('127.0.0.1', 8000, app.app)
    httpd.serve_forever()

Start the server:

python server.py

Step 5: Testing the Endpoints using CURL

Use a tool like Postman or cURL to test the endpoints.

1. Create a User (POST /users)

curl -X POST http://127.0.0.1:8000/users -d '{"name": "John Doe", "email": "john@example.com"}' -H 'Content-Type: application/json'
g
Create

2. Get a User (GET /users/1)

curl http://127.0.0.1:8000/users/1
r
Read

3. Update a User (PUT /users/1)

curl -X PUT http://127.0.0.1:8000/users/1 -d '{"name": "Jane Doe", "email": "jane@example.com"}' -H 'Content-Type: application/json'
u
Update

4. Delete a User (DELETE /users/1)

curl -X DELETE http://127.0.0.1:8000/users/1
d
Delete

Testing the Endpoints Using Postman

1. Create a User (POST /users)

  • Open Postman.
  • Select POST from the dropdown menu.
  • Enter the URL: http://127.0.0.1:8000/users.
  • Go to the Body tab and select raw. Choose JSON from the dropdown menu.
  • Enter the following JSON data:
{
"name": "Jane Doe",
"email": "jane@example.com"
}
  • Click Send.
  • You should see a response with the user's details and a status code 201 Created.

2. Get a User (GET /users/1)

  • Select GET from the dropdown menu.
  • Enter the URL:
http://127.0.0.1:8000/users/1.
  • Click Send.
  • You should see a response with the user's details if the user with ID 1 exists.

3. Update a User (PUT /users/1)

  • Select PUT from the dropdown menu.
  • Enter the URL:
http://127.0.0.1:8000/users/1.
  • Go to the Body tab and select raw. Choose JSON from the dropdown menu.
  • Enter the following JSON data:
{
"name": "Jane Doe",
"email": "jane@google.com"
}
  • Click Send.
  • You should see a response with the updated user's details.

4. Delete a User (DELETE /users/1)

  • Select DELETE from the dropdown menu.
  • Enter the URL:
http://127.0.0.1:8000/users/1.
  • Click Send.
  • You should see a response with status code 204 No Content if the user was successfully deleted.

Conclusion

To develop databases web applications, SQLAlchemy coupled with Falcon can provide you with a reliable and robust solution. This concatenation results to neat and manageable code and it is a good platform to build future expandable APIs. With this article, you can create an app using Falcon as the basis for performing CRUD operations using SQLAlchemy models.


Next Article
Practice Tags :

Similar Reads