Ir al contenido principal

FARM Stack Guide: How to Build Full-Stack Apps with FastAPI, React & MongoDB

Learn to build full-stack web apps fast with the FARM stack (FastAPI, React, MongoDB). This beginner-friendly guide goes through setup, features, and deployment in one click.
21 jul 2025  · 8 min de lectura

The full-stack FastAPI, React, MongoDB (FARM) application generator is a powerful tool designed to streamline the creation of production-grade web applications. By integrating FastAPI for the back end, React for the front end, and MongoDB as a scalable NoSQL database, the FARM generator enables Python developers to quickly scaffold robust applications with minimal setup. This tool is ideal for developers who want to focus on building features rather than configuring boilerplate code.

This article introduces the FARM application generator, explains its key features, provides step-by-step setup instructions, and demonstrates its capabilities with a real-world example: a task management application. Our goal is to show how the generator simplifies full-stack development and empowers Python developers to create scalable, production-ready applications.

If you need a refresher on MongoDB, be sure to check out DataCamp’s Introduction to MongoDB in Python course. 

What is the FastAPI Application Generator?

The FARM generator automates the creation of a complete web application stack with the following components:

  • Full-stack setup: Generates a FastAPI back end, a React front end, and a MongoDB database, seamlessly integrated for rapid development.
  • Pre-configured authentication: Includes OAuth2 with JWT, magic link authentication, and cookie management for secure user access. OAuth2 with JWT is like a secure “VIP pass” (JWT code) you get after login to access private areas.
  • Docker Compose integration: Provides pre-configured Docker Compose files for easy local development and testing.
  • Operational tools: Incorporates Celery for asynchronous task processing, Traefik for load balancing, and GitHub Actions for CI/CD, ensuring a production-ready environment.

The full features can be found in the GitHub repo.

Benefits for developers

The FARM generator offers significant advantages:

  • Time savings: Eliminates repetitive setup tasks, such as configuring authentication or database connections, allowing developers to start coding immediately.
  • Best practices: Ensures a scalable, secure, and maintainable project structure that adheres to industry standards.
  • Flexibility: Provides a customizable foundation that developers can extend to suit specific project needs.

How to Run the MongoDB FastAPI Application Generator

To illustrate the generator’s capabilities, we’ll walk through setting up a sample project. The following instructions assume you have Python 3.8+, Node.js, Docker, and Docker Compose installed.

Step-by-step setup instructions

To demonstrate the generator’s capabilities, we’ll create a sample project called task-manager. Ensure you have the following prerequisites installed:

  • Python 3.11+: Preferably 3.12, verified with python3.12 --version.
  • Node.js: For the React front end.
  • Docker Desktop: For containerized development.
  • MongoDB: Local installation (e.g., via Homebrew with brew install mongodb-community@7.0) or MongoDB Atlas (use a connection URI like mongodb+srv://:@cluster0.mongodb.net/?retryWrites=true&w=majority).
  • Cookiecutter: For generating the project template.
  • Hatch: For dependency management.
  • MongoDB Compass (optional): For database visualization.

Before you continue, make sure to create a virtual environment with /usr/local/bin/python3.12 -m venv task-manager-venv and activate it with source task-manager-venv/bin/activate.

  1. Install the cookiecutter library: pip install cookiecutter
  2. Generate the project: Use the FARM generator to create a project:
cookiecutter https://github.com/mongodb-labs/full-stack-fastapi-mongodb --no-input project_name="task-manager"
cd task-manager
  1. Install MongoDB locally or use MongoDB Atlas:
brew tap mongodb/brew
brew install mongodb-community@7.0
brew services start mongodb-community@7.0

For Atlas, sign up, create a free cluster, and get a connection string (e.g., mongodb+srv://:@cluster0.mongodb.net/?retryWrites=true&w=majority) to use in your .env file.

  1. Configure environment variables: 

Copy and edit the .env file:

cp .env.example .env
nano .env

Update with your MongoDB URI, database name, and secrets:

MONGODB_URI=mongodb://localhost:27017
MONGO_DATABASE=task_manager
SECRET_KEY=your-secret-key
FIRST_SUPERUSER=admin@task-manager.com
FIRST_SUPERUSER_PASSWORD=changethis
  1. Build and run with Docker Compose:

Ensure Docker Desktop is running, then:

docker compose build --no-cache
  1. docker compose up -d
  2. Access the application:
    • Front end: http://localhost:3000
    • Back end: http://localhost/api/v1
    • Swagger UI: http://localhost/docs (interactive API docs)
    • ReDoc: http://localhost/redoc
    • Flower: http://localhost:5555 (Celery monitoring)
    • Traefik UI: http://localhost:8090 (routing dashboard)
  3. Log in with admin@task-manager.com (password: changethis).
  4. Test authentication: Use Swagger UI (/docs) to test /auth/login or /auth/magic-link endpoints.
  5. Set up CI/CD: Push to GitHub to trigger included GitHub Actions workflows.

FastAPI/React Screenshot for front end

Explore the Generated Full-Stack Project Structure

When you use the FARM generator, it builds a task-manager project with everything neatly organized. Think of it like a pre-made house where each room has a job:

  • backend/: This is the kitchen where the FastAPI back end works. It has folders like app/ (for your API code) and conf/ (for settings) to handle tasks and data.

Directory showing the included folders

  • frontend/: This is the living room where users see your website, powered by Next.js/React. The app/ folder holds pages (e.g., about, TaskList) with files like layout.tsx (the page frame) and page.tsx (the content). The public/ folder stores things like your website’s icon.

Front-end directory

  • Other files: You’ll find docker-compose.yml (to run everything with Docker), .env (your secret settings), and .github/workflows/ (for automatic testing when you share your code).

This setup is ready to grow, and the generator adds cool tools to make development easier!

What You Can Do With the Generator’s Features

The FARM generator comes with awesome built-in tools to help you create all kinds of projects. Here’s a simple look at what they do and how they can help:

Docker Compose integration: Optimized for local development

  • What it does: Docker Compose is like a magic button that sets up and runs your whole project (back end, front end, database) with one command. It uses containers to keep everything separate and is easy to test on your computer.
  • How it helps: You can start your task-manager app by typing docker compose up -d and stop it with docker compose down. It’s perfect for trying out ideas without messing up your computer. Check how it’s running with docker compose ps—if everything’s “Up,” you’re good to go!

Example: After setting up your project, just run:

cd task-manager
docker compose up -d

Open http://localhost:3000 to see your front end, and you’re running everything locally!

Docker, where we run everything locally

Built-in authentication system

  • What it does: This adds a login system with user accounts, including a default superuser (like admin@task-manager.com with password changethis). It uses OAuth2 with JWT tokens (secure login codes) and magic links (email links to log in).
  • How it helps: You can let users sign up, log in, or use a magic link to access your app. Try it at http://localhost/docs in Swagger UI—look for /api/v1/login/oauth to test logging in. It’s great for apps where only certain people should see things, like a private task list.

Example: Log in with the default user:

  1. Go to http://localhost/docs.
  2. Find /api/v1/login/oauth, enter admin@task-manager.com and change this, and click “Execute.” You’ll get a JWT token to use for private pages!

task-manager API

The task manager API

demo for oauth api

Demo for Oauth API

return for oauth api

Return for Oauth API

FastAPI back end features

Let’s take a closer look at the key features of the FastAPI-powered back end and how it simplifies database operations, API design, and scalability.

  • MongoDB Motor: This is the engine that talks to your MongoDB database super fast, even when handling lots of requests at once.
  • MongoDB ODMantic: Think of this as a helper that makes saving and finding data in MongoDB easier, like organizing tasks into neat boxes.
  • Common CRUD support: CRUD stands for create, read, update, delete. This feature gives you ready-made tools to add, view, change, or remove data (like tasks) without starting from scratch.
  • Standards-based: It follows rules like OpenAPI and JSON Schema, so your API is clear and works with other tools or apps.
  • How it helps: You can quickly build a back end to store tasks. The generator sets this up, so you just add your own ideas, like new task features, using the code it provides.

Example: Add a quick task viewer in backend/app/api/tasks.py:

from fastapi import APIRouter, Depends
from odmantic import AIOEngine, Model
from motor.motor_asyncio import AsyncIOMotorClient
router = APIRouter(prefix="/tasks", tags=["tasks"])
class Task(Model):
    title: str
async def get_db():
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    return AIOEngine(client, database="task_manager")
@router.get("/")  # View all tasks
async def get_tasks(db: AIOEngine = Depends(get_db)):
    return await db.find(Task)

Test it at http://localhost/api/v1/tasks after rebuilding with docker compose up --build.

Next.js/React front end

The React front end is where users interact with your app. Let’s explore how it’s structured and what tools it includes to help you build polished, responsive pages.

  • Middleware authorization: This acts like a gatekeeper, checking if users are logged in before they see certain pages (e.g., only logged-in users see /TaskList).
  • Form validation with React Hook Form: This makes sure forms (like a task-adding form) have the right info before saving, so no empty tasks sneak in.
  • State management with Redux: This keeps track of things, like which tasks are selected, making your app smooth and fast even with lots of data.
  • CSS and templates with TailwindCSS, HeroIcons, and HeadlessUI: These are like pre-made design tools. TailwindCSS styles your pages, HeroIcons adds cool icons, and HeadlessUI gives you buttons and menus that work great.
  • How it helps: You can build a nice-looking task page with easy forms and secure access. The generator sets up the design, so you can focus on adding tasks or other features.

Example: Add a simple task form in frontend/app/TaskList/page.tsx:

import { useState } from 'react';
export default function TaskList() {
  const [task, setTask] = useState({ title: '' });
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    fetch('http://localhost/api/v1/tasks', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(task),
    });
    setTask({ title: '' });
  };
  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold">Add Task</h1>
      <form onSubmit={handleSubmit}>
        <input
          className="border p-2"
          value={task.title}
          onChange={e => setTask({ title: e.target.value })}
          placeholder="Task name"
        />
        <button className="bg-blue-500 text-white p-2" type="submit">Add</button>
      </form>
    </div>
  );
}

Visit http://localhost:3000/TaskList to add a task.

Adding task

Growing your task manager

The generator gives you a solid start for a task manager. For example, you can:

  • Add a button to mark tasks as done using the CRUD tools.
  • Use the authentication to keep your task list private.
  • Style it with TailwindCSS to make it look awesome.
  • Set up Celery to send task reminders via email.

Other ideas to explore

With these features, you can build more than just a task manager:

  • Blog or website: Store posts in MongoDB, use FastAPI to show them, and design a cool site with Next.js.
  • Online store: Save products in MongoDB, handle orders with Celery, and create a shop page with Next.js.
  • Live updates: Show real-time info (like a game score) using MongoDB, FastAPI’s live features, and a Next.js dashboard.

Conclusion

The FARM application generator streamlines full-stack development by providing a pre-configured, production-ready stack that integrates FastAPI, React, and MongoDB. Its automation of setup tasks, adherence to best practices, and flexible architecture make it an invaluable tool for Python developers. Whether you’re building a task manager or a complex web application, the FARM generator accelerates development and ensures scalability. Try it out today by following the setup instructions, and explore the full documentation on the GitHub repository to unlock its potential!

If you want to learn more, check out these helpful resources:

  • Official repository: Explore the source code, read the full documentation, and see updates or contribute.
  • FastAPI documentation: Learn more about FastAPI’s features and how it powers the back end.
  • Introduction to FastAPI Course: Build robust, production-grade APIs with FastAPI, mastering HTTP operations, validation, and async execution to create efficient data and ML pipelines.

FAQs

Why should I use the FARM generator?

It helps developers quickly start projects with industry-standard practices, including security (OAuth2/JWT), scalability (Docker/Celery), and maintainability. Instead of configuring everything manually, you can focus on building features right away.

Can I use the FARM generator if I’m new to web development?

Yes! The generator handles complex setup (like authentication and Docker) for you, so beginners can focus on learning FastAPI, React, or MongoDB without getting stuck on configuration. However, basic knowledge of Python and JavaScript will help you customize the project.

Can I use this for mobile app development?

While the FARM generator creates a web application, you can use the FastAPI back end with mobile apps by calling its APIs. The React front end can also be adapted for mobile using frameworks like React Native, though this would require additional setup.

Can I deploy my app online for others to use?

The generator includes Docker and CI/CD setup to help deploy your app to services like AWS, GCP, DigitalOcean, Heroku, and more!

Can I use this without knowing Docker?

Yes, but Docker makes things much easier. Without Docker, you would need to install MongoDB separately and run servers manually.


Karen Zhang's photo
Author
Karen Zhang
LinkedIn

Karen is a Data Engineer with a passion for building scalable data platforms. She has experience in infrastructure automation with Terraform and is excited to share her learnings in blog posts and tutorials. Karen is a community builder, and she is passionate about fostering connections among data professionals.

Temas

Top DataCamp Courses

Curso

Introduction to MongoDB in Python

3 h
22.2K
Learn to manipulate and analyze flexibly structured data with MongoDB.
Ver detallesRight Arrow
Comienza el curso
Ver másRight Arrow
Relacionado

Tutorial

FastAPI Tutorial: An Introduction to Using FastAPI

Explore the FastAPI framework and discover how you can use it to create APIs in Python
Moez Ali's photo

Moez Ali

Tutorial

Getting Started with Microsoft Fabric: A Practical Guide

This tutorial walks you through Microsoft Fabric, showing you how to set up, connect data, build pipelines, and collaborate—all in one practical guide!
Kurtis Pykes 's photo

Kurtis Pykes

Tutorial

Running MongoDB in Docker: A Complete Guide with Examples

This guide walks you through running MongoDB in Docker, covering both quick command-line deployments and full Docker Compose configurations. It’s perfect for developers looking to self-host or experiment locally without immediately jumping into cloud hosting.
Nic Raboy's photo

Nic Raboy

Tutorial

Getting Started with Gemini Fullstack LangGraph

Set up a full-stack deep AI research assistant, featuring a React frontend and a LangGraph backend.
Abid Ali Awan's photo

Abid Ali Awan

Tutorial

Build Your First AWS CDK Stack: A Beginner-Friendly Tutorial

Learn how to build and deploy your first AWS CDK stack using Python. This beginner-friendly guide covers setup, constructs, deployment, testing, and CI/CD.
Rahul Sharma's photo

Rahul Sharma

Tutorial

Docker Compose Guide: Simplify Multi-Container Development

Master Docker Compose for efficient multi-container application development. Learn best practices, scaling, orchestration, and real-world examples.
Derrick Mwiti's photo

Derrick Mwiti

Ver másVer más