Building Microservices with FastAPI and React
Dinesh Pratap Singh
Posted on February 14, 2024
Introduction
Microservices architecture is a design pattern for developing applications as a suite of small services, each running in its own process and communicating with lightweight mechanisms. In this article, we will be building a simple product management system using FastAPI for the backend and React for the frontend.
Backend with FastAPI
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
Setting Up FastAPI
First, install FastAPI and an ASGI server, such as Uvicorn.
pip install fastapi uvicorn
Creating the CRUD Operations
Let’s create a simple CRUD (Create, Read, Update, Delete) operations for managing products.
Python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Product(BaseModel):
id: int
name: str
price: float
products = []
@app.post("/product/")
def create_product(product: Product):
products.append(product.dict())
return product.dict()
@app.get("/product/")
def get_products():
return products
@app.get("/product/{product_id}")
def get_product(product_id: int):
product = next((product for product in products if product["id"] == product_id), None)
return product
@app.put("/product/{product_id}")
def update_product(product_id: int, product: Product):
index = next((index for (index, d) in enumerate(products) if d["id"] == product_id), None)
products[index] = product.dict()
return products[index]
@app.delete("/product/{product_id}")
def delete_product(product_id: int):
index = next((index for (index, d) in enumerate(products) if d["id"] == product_id), None)
return products.pop(index)
Frontend with React
React is a JavaScript library for building user interfaces. It allows you to compose complex UIs from small and isolated pieces of code called “components”.
Setting Up React
First, install Node.js and npm. Then, use Create React App to set up a new React project.
npx create-react-app product-app
Consuming the REST API
We will use the fetch function built into most modern browsers to consume our FastAPI backend.
import React, { useEffect, useState } from 'react';
function App() {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch('/product/')
.then(response => response.json())
.then(data => setProducts(data));
}, []);
return (
<div>
{products.map(product => (
<div key={product.id}>
<h2>{product.name}</h2>
<p>{product.price}</p>
</div>
))}
</div>
);
}
export default App;
Conclusion
In this article, we have seen how to build a simple product management system using FastAPI and React.
References
Posted on February 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.