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:
- Models: Define and structure your data.
- Views: Send responses to the client (in APIs, this is typically JSON).
- Controllers: Handle requests, interact with models, and return responses.
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:
- Installs FastAPI: The core library to build your application.
- Installs Uvicorn: A server that runs your FastAPI app.
- Sets up a virtual environment: A contained environment for your project with dependencies listed in Pipfile and Pipfile.lock.
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
- Create a new file called
main.py:
touch main.py
- 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
- Start the server:
pipenv run uvicorn main:app --reload
- 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.
-
Navigate to the root directory of your project.
-
Create directories for models and controllers:
mkdir models controllers
- Create placeholder files for your models and controllers:
touch models/tea_data.py controllers/teas.py
models/tea_data.py: This file will define the data structure for your app.controllers/teas.py: This file will handle requests and manage logic for the app.
With our Project structure in place, next we will build out our models and controllers.