Python based FastAPI for Java based Spring Boot Developers

Overview

FastAPI is a modern Python framework for building REST APIs and backend services. It is designed around Python type hints, asynchronous programming, and automatic API documentation generation.

For Java developers coming from Spring Boot, FastAPI feels lightweight, explicit, and highly productive while still supporting enterprise-grade REST services.

FastAPI offers:

  • Lightweight and fast startup
  • Async support using Python asyncio
  • Automatic OpenAPI and Swagger documentation
  • Built-in request validation using Pydantic
  • Dependency injection support
  • Minimal boilerplate
  • Excellent developer productivity
  • Suitable for microservices and APIs

Introduction

In this article, we will show how to create a FastAPI based REST application. The concepts will be explained from the perspective of Spring Boot developers.

The example project uses:

  • FastAPI
  • SQLAlchemy ORM
  • Pydantic models
  • SQLite database

Code location:

python-rest-services GitHub Repository


Application Startup

The following is conceptually similar to Spring Boot’s @SpringBootApplication annotated class and SpringApplication.run().

FastAPI

from fastapi import FastAPI
from app.routes.user_routes import router as user_router
from app.routes.order_routes import router as order_router

app = FastAPI()

app.include_router(user_router)
app.include_router(order_router)

Spring Boot Equivalent

@SpringBootApplication
public class Application {
   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }
}

In FastAPI:

  • FastAPI() creates the application instance
  • include_router() registers REST routes
  • The framework automatically exposes Swagger UI

Swagger UI is available at:

http://localhost:8000/docs

This is conceptually similar to Spring Boot applications using:

  • springdoc-openapi
  • springfox swagger

Routes

Routes in FastAPI are conceptually similar to Spring Boot Controllers.

FastAPI

from fastapi import APIRouter, HTTPException
from typing import List

router = APIRouter(prefix="/users", tags=["Users"])

@router.get("/", response_model=List[UserResponse])
def get_users():
    return user_service.get_all_users()

@router.get("/{user_id}")
def get_user(user_id: int):
    user = user_service.get_user(user_id)

    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    return user

@router.post("/")
def create_user(user: UserCreate):
    return user_service.create_user(user)

Spring Boot Equivalent

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping
    public List<User> getUsers() {
        return userService.getUsers();
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
}

Similarities:

  • @router.get() is similar to @GetMapping
  • @router.post() is similar to @PostMapping
  • Path parameters work similarly
  • JSON serialization is automatic

Request Validation

FastAPI uses Pydantic models for request validation.

FastAPI

from pydantic import BaseModel

class UserCreate(BaseModel):
    first_name: str
    last_name: str
    email: str

This is similar to Spring Boot DTO validation.

Spring Boot Equivalent

public class UserRequest {
    @NotBlank
    private String firstName;

    @NotBlank
    private String lastName;

    @Email
    private String email;
}

FastAPI automatically:

  • validates requests
  • returns validation errors
  • generates API schema documentation

without extra configuration.


Database Models

FastAPI commonly uses SQLAlchemy ORM.

SQLAlchemy Model

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

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    first_name = Column(String)
    last_name = Column(String)
    email = Column(String)

Spring Boot Equivalent

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue
    private Long id;

    private String firstName;
    private String lastName;
    private String email;
}

Repository Layer

FastAPI applications often use SQLAlchemy sessions directly.

FastAPI

def get_user(db: Session, user_id: int):
    return db.query(User)\
             .filter(User.id == user_id)\
             .first()

Spring Boot Equivalent

public interface UserRepository
    extends JpaRepository<User, Long> {
}

Spring Boot provides more abstraction through Spring Data JPA, while FastAPI typically uses SQLAlchemy queries directly.


Dependency Injection

FastAPI also supports dependency injection.

FastAPI

from fastapi import Depends

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

@router.get("/")
def get_users(db: Session = Depends(get_db)):
    return user_service.get_users(db)

Spring Boot Equivalent

@Autowired
private UserService userService;

FastAPI dependency injection is:

  • explicit
  • function-based
  • lightweight

compared to Spring’s annotation-driven dependency injection.


Automatic API Documentation

One of FastAPI’s strongest features is automatic API documentation generation.

Available automatically:

  • Swagger UI
  • OpenAPI specification
  • ReDoc documentation

Endpoints:

/docs
/redoc
/openapi.json

In Spring Boot, this usually requires additional libraries such as:

  • springdoc-openapi
  • springfox

FastAPI vs Spring Boot Comparison Summary

Feature FastAPI Spring Boot
Language Python Java
Startup Time Very Fast Moderate
Boilerplate Minimal More
Async Support Native asyncio WebFlux/Reactor
Dependency Injection Lightweight Extensive
API Docs Built-in Additional libraries
Ecosystem Growing Extremely Mature
ORM SQLAlchemy Hibernate/JPA
Enterprise Integrations Moderate Extensive
Learning Curve Easier Steeper

When FastAPI Works Well

FastAPI is an excellent choice for:

  • lightweight REST APIs
  • AI/ML services
  • microservices
  • async applications
  • rapid prototyping
  • Python-centric backend systems

When Spring Boot Still Shines

Spring Boot continues to be a strong choice for:

  • large enterprise systems
  • complex integrations
  • highly standardized enterprise architectures
  • large teams already invested in JVM ecosystem

Conclusion

For Java developers exploring Python backend development, FastAPI provides a modern and productive framework with many familiar concepts from Spring Boot:

  • REST controllers
  • dependency injection
  • request validation
  • ORM support
  • service layers

At the same time, FastAPI offers:

  • less boilerplate
  • faster development
  • async-first architecture
  • automatic documentation generation

For developers already familiar with Spring Boot concepts, learning FastAPI is relatively straightforward and highly rewarding.