FastAPI is built on top of Starlette and Pydantic. Starlette is a lightweight ASGI framework, which allows FastAPI to handle asynchronous requests efficiently. Pydantic is used for data validation and serialization, ensuring that the data received and sent by the API is in the correct format. FastAPI uses type hints in Python to define the API endpoints and data models, which provides automatic documentation generation through Swagger UI and ReDoc.
Spring Boot is an extension of the Spring framework. It aims to simplify the development of Spring applications by providing a set of pre - configured dependencies and auto - configuration features. Spring Boot uses the Inversion of Control (IoC) and Dependency Injection (DI) principles, which help in decoupling components and making the application more modular. It also has a built - in embedded server (such as Tomcat, Jetty), allowing developers to run the application as a standalone Java application.
First, install FastAPI and Uvicorn (a server for running FastAPI applications) using pip:
pip install fastapi uvicorn
Here is a simple example of a FastAPI application:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
To run the application, use the following command:
uvicorn main:app --reload
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/")
public String readRoot() {
return "{\"Hello\": \"World\"}";
}
@GetMapping("/items/{item_id}")
public String readItem(@PathVariable int item_id, @RequestParam(required = false) String q) {
return "{\"item_id\": " + item_id + ", \"q\": \"" + q + "\"}";
}
}
Run the main
method in the DemoApplication
class.
async
and await
keywords to handle asynchronous operations, such as database queries or external API calls.import asyncio
from fastapi import FastAPI
app = FastAPI()
async def simulate_db_call():
await asyncio.sleep(1)
return {"data": "DB result"}
@app.get("/async")
async def async_endpoint():
result = await simulate_db_call()
return result
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
import time
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
return http.build();
}
}
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
TestClient
provided by FastAPI to write unit and integration tests for your API endpoints.from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
application.properties
or application.yml
files to manage application configuration. You can also use Spring Cloud Config for centralized configuration management in a microservices environment.FastAPI and Spring Boot are both excellent frameworks for building web APIs, but they have different characteristics. FastAPI is a great choice for Python developers who want a fast and modern framework with easy - to - use features for building APIs. It is well - suited for projects that require high performance and asynchronous processing. Spring Boot, on the other hand, is a mature and powerful framework for Java developers. It has a large ecosystem and provides comprehensive support for enterprise - level features such as security, database access, and distributed systems. The choice between FastAPI and Spring Boot depends on the specific requirements of your project, the programming language preference, and the existing technology stack.