HomePython FastAPIBuilding a FastAPI Login and Registration RESTful API

Building a FastAPI Login and Registration RESTful API

- Advertisement -spot_img

FastAPI Login and Registration RESTful API: FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. In this tutorial, we will create a RESTful API for user login and registration using FastAPI. We’ll cover everything from setting up the project to implementing and testing the endpoints.

What is RESTful API


A RESTful API (Representational State Transfer) is an architectural style for designing networked applications. It uses a stateless, client-server communication model over HTTP. RESTful APIs allow different systems to interact with each other over the internet in a scalable and efficient way.

Key principles of REST include:

  1. Stateless: Each request from a client to a server must contain all the information the server needs to fulfill the request (i.e., no session state is stored on the server).
  2. Client-Server Architecture: The client and the server are separate entities. The client makes requests, and the server responds with resources. This separation allows for better scalability and flexibility.
  3. Uniform Interface: REST APIs are designed to have a consistent interface across different resources, simplifying interactions. It typically involves using standard HTTP methods (GET, POST, PUT, DELETE, PATCH) for different operations.
  4. Resource-Based: Resources (like data objects) are identified by URIs (Uniform Resource Identifiers). A resource could represent an object, a collection, or an action. Resources are manipulated using standard HTTP methods.
  5. Representation: Clients interact with the representation of the resource, not the resource itself. This representation could be in formats like JSON, XML, or HTML.
  6. Stateless Communication: Each API request must be independent and carry enough context for the server to process it, without relying on previous requests.
  7. Cacheable: Responses from the server can be marked as cacheable or non-cacheable to optimize performance.

HTTP Methods Used in RESTful APIs:

  • GET: Retrieve data from the server (e.g., get a list of users).
  • POST: Create new resources on the server (e.g., create a new user).
  • PUT: Update an existing resource (e.g., update a user’s information).
  • DELETE: Remove a resource (e.g., delete a user).
  • PATCH: Apply partial updates to a resource.

Example of RESTful API:

  • GET /users: Fetch a list of users.
  • GET /users/{id}: Fetch details for a specific user by their ID.
  • POST /users: Create a new user.
  • PUT /users/{id}: Update user data for the given ID.
  • DELETE /users/{id}: Delete a user by ID.

Advantages of RESTful APIs:

  • Simple and lightweight, as they often rely on HTTP and standard web protocols.
  • Easy to scale and maintain.
  • Supported by many programming languages and frameworks.
  • Decouples client and server, allowing independent evolution of each.

Would you like to dive deeper into how to implement or use RESTful APIs?

Prerequisites FastAPI Login and Registration RESTful API

Before diving in, ensure you have the following installed:

  • Python 3.7 or later
  • pip (Python package installer)
  • A virtual environment tool (optional but recommended)

Project Setup

  1. Create a new directory for your project: mkdir fastapi-auth && cd fastapi-auth
  2. Initialize a virtual environment (optional): python -m venv venv source venv/bin/activate # For Linux/macOS venvScriptsactivate # For Windows
  3. Install FastAPI and Uvicorn: pip install fastapi uvicorn
  4. Create the required files: touch main.py models.py schemas.py database.py

Setting Up the Database

We’ll use SQLite for simplicity and SQLAlchemy for ORM (Object-Relational Mapping).

  1. Install SQLAlchemy and databases library: pip install sqlalchemy databases pydantic bcrypt
  2. Configure the database in database.py: from sqlalchemy import create_engine, MetaData DATABASE_URL = "sqlite:///./users.db" engine = create_engine(DATABASE_URL) metadata = MetaData() from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()

Creating Models

Define your database models in models.py:

from sqlalchemy import Column, Integer, String
from database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    email = Column(String, unique=True, index=True)
    password = Column(String)

Schemas for Validation FastAPI Login and Registration RESTful API

Define the request and response schemas in schemas.py:

from pydantic import BaseModel

class UserBase(BaseModel):
    username: str
    email: str

class UserCreate(UserBase):
    password: str

class UserOut(UserBase):
    id: int

    class Config:
        orm_mode = True

Main Application

Implement the API logic in main.py:

from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy.orm import Session
from database import engine, Base
from models import User
from schemas import UserCreate, UserOut
from sqlalchemy.exc import IntegrityError
import bcrypt
from database import SessionLocal

Base.metadata.create_all(bind=engine)

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post("/register", response_model=UserOut)
def register(user: UserCreate, db: Session = Depends(get_db)):
    hashed_password = bcrypt.hashpw(user.password.encode('utf-8'), bcrypt.gensalt())
    db_user = User(username=user.username, email=user.email, password=hashed_password.decode('utf-8'))
    try:
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
    except IntegrityError:
        raise HTTPException(status_code=400, detail="Username or email already registered")
    return db_user

@app.post("/login")
def login(username: str, password: str, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.username == username).first()
    if not user or not bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
        raise HTTPException(status_code=401, detail="Invalid username or password")
    return {"message": "Login successful"}

Running the Application

Start the FastAPI application using Uvicorn:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs to explore the API using the auto-generated Swagger UI.


Testing the Endpoints FastAPI Login and Registration RESTful API

  1. Register a user:
    • Endpoint: POST /register
    • Body: { "username": "testuser", "email": "test@example.com", "password": "password123" }
  2. Login with the registered user:
    • Endpoint: POST /login
    • Body: { "username": "testuser", "password": "password123" }

FastAPI Login and Registration RESTful API

You now have a fully functional FastAPI application with login and registration capabilities. FastAPI’s simplicity and performance make it an excellent choice for building RESTful APIs. Expand this project by adding JWT-based authentication, user roles, and more complex features for real-world applications.

Top 10 Websites to Learn the Latest Technology in 2025

Stay Connected
16,985FansLike
2,458FollowersFollow
61,453SubscribersSubscribe
Must Read
Related News

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here