Close Menu
IOupdate | IT News and SelfhostingIOupdate | IT News and Selfhosting
  • Home
  • News
  • Blog
  • Selfhosting
  • AI
  • Linux
  • Cyber Security
  • Gadgets
  • Gaming

Subscribe to Updates

Get the latest creative news from ioupdate about Tech trends, Gaming and Gadgets.

[contact-form-7 id="dd1f6aa" title="Newsletter"]
What's Hot

Using MITRE D3FEND to strengthen you home network

September 8, 2025

Speed Isn’t Everything When Buying SSDs

September 8, 2025

Debian 13.1 Released With An Initial Batch Of Fixes

September 8, 2025
Facebook X (Twitter) Instagram
Facebook Mastodon Bluesky Reddit
IOupdate | IT News and SelfhostingIOupdate | IT News and Selfhosting
  • Home
  • News
  • Blog
  • Selfhosting
  • AI
  • Linux
  • Cyber Security
  • Gadgets
  • Gaming
IOupdate | IT News and SelfhostingIOupdate | IT News and Selfhosting
Home»Selfhosting»How to Install Fast API with MongoDB on Ubuntu 24.04
Selfhosting

How to Install Fast API with MongoDB on Ubuntu 24.04

AndyBy AndyMay 28, 2025No Comments4 Mins Read
How to Install Fast API with MongoDB on Ubuntu 24.04


Unlock the Power of Self-Hosting with FastAPI and MongoDB on Ubuntu 24.04

In today’s digital landscape, self-hosting offers unmatched control and customization over your applications. This comprehensive guide walks you through the seamless integration of FastAPI with MongoDB on Ubuntu 24.04. You’ll dive into the nuances of setting up your own API and executing CRUD operations effortlessly. If you’re ready to take charge of your hosting environment, keep reading to unleash the capabilities of FastAPI!

What You Will Learn

By the end of this tutorial, you will have:

  • Installed FastAPI and MongoDB on Ubuntu 24.04.
  • Set up a virtual environment for your FastAPI project.
  • Established a simple CRUD API with FastAPI and MongoDB.

Prerequisites

  • An Ubuntu 24.04 system.
  • A non-root user with administrator privileges.

Installing MongoDB

Before diving into FastAPI, it’s essential to have MongoDB installed. Begin by updating your package index and installing the necessary tools:

sudo apt update && sudo apt install gnupg curl -y

Afterward, add the GPG key and the MongoDB repository:

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Now install MongoDB:

sudo apt update && sudo apt install mongodb-org

Start the MongoDB service and enable it to run at startup:

sudo systemctl enable --now mongod

Check the status to confirm it’s running:

sudo systemctl status mongod

Setting Up a Python Environment

With MongoDB in place, the next step is to configure your Python environment:

sudo apt install python3 python3-pip python3-venv

Create and navigate into a project directory:

mkdir -p ~/app; cd ~/app

Now create and activate a virtual environment:

python3 -m venv .venv
source .venv/bin/activate

Creating Your FastAPI Project

Install FastAPI and Uvicorn:

pip3 install fastapi uvicorn

Create the necessary project structure:

mkdir -p server/{models,routes} && touch main.py server/{app.py,database.py} server/models/itemModels.py server/routes/item.py

Building Your API

Defining the Application

Open the server/app.py file and add the following code:

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello FastAPI!"}

Implementing CRUD Operations

The next step is to implement CRUD operations in server/database.py. You will need the motor MongoDB driver:

pip3 install motor

In the database.py file, add your MongoDB connection logic:

from motor.motor_asyncio import AsyncIOMotorClient

MONGODB_HOST = "mongodb://localhost:27017"
connection = AsyncIOMotorClient(MONGODB_HOST)
database = connection.items
item_collection = database.get_collection("item_collection")

Creating Data Models with Pydantic

Utilize pydantic for data validation. Inside server/models/itemModels.py, define your item schema:

from pydantic import BaseModel, Field
from typing import Optional

class Item(BaseModel):
    name: str
    category: str
    stocks: int
    price: int = Field(gt=0)

Setting Up API Routes

To enable interaction with your data, define API endpoints in server/routes/item.py. You will create the endpoints for adding, retrieving, updating, and deleting items.

  • @router.post("/") for adding new items.
  • @router.get("/") for retrieving all items.
  • @router.get("/{id}") for getting a specific item.
  • @router.put("/{id}") for updating items.
  • @router.delete("/{id}") for deleting items.

Testing Your API

Run your FastAPI application:

python3 main.py

Navigate to http://SERVERIP:8080/docs to interact with your API documentation, elegantly provided by Swagger UI.

Conclusion

Congratulations! You’ve successfully self-hosted an API using FastAPI and MongoDB on Ubuntu 24.04. This guide not only empowered you to leverage the full potential of self-hosting but also allowed you to experiment with building and managing your API. With FastAPI’s performance and MongoDB’s flexibility, you’re now equipped to create robust applications. Don’t hesitate to explore more features and expand your API further!

FAQ

Question 1: What are the benefits of self-hosting?

Self-hosting provides greater control over data, customization options, and enhanced privacy. Users can manage their server settings without dependency on third-party services.

Question 2: Can I use other databases with FastAPI?

Absolutely! FastAPI is compatible with various databases like PostgreSQL, MySQL, and SQLite. You can integrate them easily based on your application requirements.

Question 3: How do I secure my FastAPI application?

Consider implementing authentication and authorization strategies, such as OAuth2. Also, ensure to implement HTTPS for secure data transmission when deploying your application.



Read the original article

0 Like this
API fast install MongoDB Ubuntu
Share. Facebook LinkedIn Email Bluesky Reddit WhatsApp Threads Copy Link Twitter
Previous ArticleIntel APX Ready With Linux 6.16, Outdated Intel CPU Microcode Reporting Merged
Next Article Better Than Man pages? These Tools Help You Understand Linux Commands

Related Posts

Selfhosting

5 Storage Projects to Supercharge Your Home Lab This Weekend

August 24, 2025
Linux

AMD Ryzen AI 5 340 Windows 11 vs. Ubuntu Linux Performance For Budget “Krackan Point” Laptops Review

August 22, 2025
Selfhosting

Awesome List Updates on Jul 14, 2025

August 22, 2025
Add A Comment
Leave A Reply Cancel Reply

Top Posts

AI Developers Look Beyond Chain-of-Thought Prompting

May 9, 202515 Views

6 Reasons Not to Use US Internet Services Under Trump Anymore – An EU Perspective

April 21, 202512 Views

Andy’s Tech

April 19, 20259 Views
Stay In Touch
  • Facebook
  • Mastodon
  • Bluesky
  • Reddit

Subscribe to Updates

Get the latest creative news from ioupdate about Tech trends, Gaming and Gadgets.

About Us

Welcome to IOupdate — your trusted source for the latest in IT news and self-hosting insights. At IOupdate, we are a dedicated team of technology enthusiasts committed to delivering timely and relevant information in the ever-evolving world of information technology. Our passion lies in exploring the realms of self-hosting, open-source solutions, and the broader IT landscape.

Most Popular

AI Developers Look Beyond Chain-of-Thought Prompting

May 9, 202515 Views

6 Reasons Not to Use US Internet Services Under Trump Anymore – An EU Perspective

April 21, 202512 Views

Subscribe to Updates

Facebook Mastodon Bluesky Reddit
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions
© 2025 ioupdate. All Right Reserved.

Type above and press Enter to search. Press Esc to cancel.