FastAPI MVC CRUD Build Create the Server

Learning Objective: By the end of this lesson, you will be able to set up a FastAPI server and create the basic structure for a FastAPI MVC CRUD application, including controller and model files.

Introduction

In this lesson, you’ll build your first FastAPI application using the Model-View-Controller (MVC) design pattern. This means you’ll organize your code into:

Let’s start by setting up your project and ensuring your FastAPI server is running correctly.

Review your installation

Before you begin, let’s confirm what the following command does:

pipenv install fastapi uvicorn

What we installed:

Tip: If you clone a FastAPI project, running pipenv install will install all necessary dependencies automatically.

If you need a refresher, check out the pipenv guide.

Create the FastAPI entry point

  1. Create a new file called main.py:
touch main.py
  1. Add the follwoing code :
# main.py

from fastapi import FastAPI

app = FastAPI()


@app.get('/')
def home():
    # Hello world function
    return {'message': 'Hello World!'}

Testing the Application

  1. Start the server:
 pipenv run uvicorn main:app --reload
  1. Open your browser and go to: http://127.0.0.1:8000

You should see:

{
  "message": "Hello World!"
}

Make sure you see the Hello World! message before proceeding.

Prepare the MVC directory structure

To build an MVC application, you need to organize your code into folders for models and controllers.

Open a new terminal window while keeping the server running.

  1. Navigate to the root directory of your project.

  2. Create directories for models and controllers:

mkdir models controllers
  1. Create placeholder files for your models and controllers:
touch models/tea_data.py controllers/teas.py

With our Project structure in place, next we will build out our models and controllers.