avatarShubhendu ghosh

Summary

The provided content is a step-by-step tutorial on building an admin panel for FastAPI applications using sqlalchemy for database operations and sqladmin for the admin interface.

Abstract

The article offers a comprehensive guide for developers to create an admin panel for FastAPI applications. It begins with an introduction to the FastAPI framework and the benefits of using sqlalchemy and sqladmin for backend and admin interface development, respectively. The tutorial is structured into seven steps, starting from the installation of necessary packages, setting up the database, creating models, and configuring the main application file. It also covers the creation of an admin authentication system, the implementation of model views, and the final steps of migrating models to the database and running the application. The author emphasizes the importance of using sqladmin for admin services and provides code snippets for each step, ensuring a clear understanding of the process. The conclusion suggests potential customizations and invites readers to follow the author for similar content.

Opinions

  • The author positions sqlalchemy and sqladmin as essential tools for building a feature-rich admin panel with FastAPI.
  • There is a strong recommendation to adhere to the tutorial's steps and use the specified libraries for the guide to be effective.
  • The author expresses confidence that following the tutorial will result in an admin panel that meets or exceeds expectations.
  • The inclusion of authentication and authorization mechanisms is presented as a critical component of the admin panel.
  • Customization options are highlighted as a way to further enhance the admin interface beyond the provided tutorial.
  • The author encourages engagement with their content by inviting readers to follow them on social media platforms for more tutorials and insights.

Building an Admin Panel for FastAPI Apps | Step-by-Step Tutorial | Sqladmin

Photo by Stanley Dai on Unsplash

Introduction

FastAPI, known for it’s lightning-fast performance and intuitive design, has emerged as a favorite among developers seeking to streamline their backend processes. Today in this article we will see how can we create an admin panel. This is a complete step-by-step tutorial will cover everything you need to build a feature-rich admin interface from scratch. Let’s harness the power of FastAPI and embark on a journey to build an admin panel that not only meets but exceeds your expectations. Let’s dive in!

Step -1 : Installation

Before we start let’s clear the dependencies. we will use sqlalchemy for database operation and sqladmin for admin service. These two are very important because if you are using any other database operation library or other admin then this article might not help you.

pip install sqlalchemy
pip install sqladmin
pip install sqladmin[full]

Step-2 : Create the Database

create a example_database.py file and create or link your database with sqlalchemy

from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker



engine = create_engine("sqlite:///example.db",isolation_level='AUTOCOMMIT')

session = sessionmaker(bind=engine)
Base = declarative_base()

Step-3 : Create Models

create a models.py file and create your models(Tables)

from sqlalchemy import Column, Integer, String, Boolean
from example_database import Base, engine, session


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    email = Column(String)
    username = Column(String)
    password = Column(String)
    firstname = Column(String)
    lastname = Column(String)
    is_admin = Column(Boolean)


Base.metadata.create_all(engine)

Step-4: Create main.py

Now create a file named main.py. This will be the main file of your fastapi app.

from fastapi import FastAPI
from admin import create_admin #we will create this file in a while


app = FastAPI(title="AppName")
admin = create_admin(app)  # we will write this function in a while


# list your APIs here
@app.get("/")
async def hello_world():
    return {"message":"Hello World"}

Step-5: Create admin.py

Now create another file named admin.py. all the admin actions will be controlled from here. Also authentication will be handled from here.

from sqladmin import Admin, ModelView
from example_database import engine, session
from models.py import Users
from sqladmin.authentication import AuthenticationBackend
from starlette.requests import Request


#This page will implement the authentication for your admin pannel
class AdminAuth(AuthenticationBackend):

    async def login(self, request: Request) -> bool:
        form = await request.form()
        username= form.get("username")
        password= form.get("password")
        session = session()
        user = session.query(Users).filter(Users.username == username).first()
        if user and password== user.password:
            if user.is_admin:
                request.session.update({"token": beta_user.username})
                return True
        else:
            False

    async def logout(self, request: Request) -> bool:
        request.session.clear()
        return True

    async def authenticate(self, request: Request) -> bool:
        token = request.session.get("token")
        return token is not None


# create a view for your models
class UsersAdmin(ModelView, model=Users):
    column_list = [
        'id', 'email', 'first_name', 'last_name', 'is_admin'
    ]


# add the views to admin
def create_admin(app):
    authentication_backend = AdminAuth(secret_key="supersecretkey")
    admin = Admin(app=app, engine=engine, authentication_backend=authentication_backend)
    admin.add_view(UsersAdmin)
    
    return admin

That’t it . we are finished with the coding. now just a few steps are left.

Step-6 : Migrate your models to database

run this command to create a migration script.

alembic revision --autogenerate -m "Add table Users"

Then apply the migration to move your model to your database

alembic upgrade head

Step-7 : Run the app

Now run the app

uvicorn main:app --reload

if everything is okay then go to

http://localhost:8000/admin

You should see a page that will ask you for username and password

Once you enter your username and password you’ll be able to enter your admin panel.

Conclusion

That was it. If you want more customization then you can add your own template inside the folder “templates/sqladmin” with the name “login.html” etc to have your own login page. In admin you can do all kinds of operations including edit, delete, add etc.

please follow me for more of such content Twitter, Github, Linkedin

Reference:

Link, Link

Fastapi
Sqladmin
Fastapi Admin
Django Admin
Recommended from ReadMedium