Introduction
This article in the series will cover setting up a basic FastAPI project. The best tutorial for learning FastAPI is on their website. However, for the sake of continuity, I'll detail some steps here:
- Setting up a virtual environment
- Downloading necessary modules
- Creating project files
- Inserting starter code
Virtual Environment
First, create a new directory. Or, you can navigate (in a terminal or command shell) to the directory where you wish to create the project.
I made a directory called fastapi_tutorial
.
Next, if you don't have it downloaded already, download virtualenv
.
$ pip3 install virtualenv
This should install the package into your global Python interpreter or your current activated environment.
Now, we can create a new virtual environment for the project.
pip freeze
later to easily grab or package names and version.In the terminal run the command:
$ virtualenv venv
After the command is done, a new virtual environment folder is added to our project folder. The name of our new environment is venv
.
Finally, we need to activate the environment with:
$ source venv/bin/activate
Install Packages
Next, we need to install the packages necessary to run FastAPI locally.
$ pip3 install fastapi uvicorn
The uvicorn
package is for running the local server. Additionally, installing fastapi
installed:
pydantic
starlette
typing-extensions
Create the Server File
Inside the root of the project, create the file main.py
. Paste the below code into the file:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
In this file, we create our API and store it in the app
variable.
The "/"
route is the index of our API. We add this route as the only route available. If you visit this route, you'll receive the return value, {"message": "Hello World"}
.
Start the Server
With the virtual environment active, we can start the development server to run locally.
In the terminal, in the root directory, run the command:
uvicorn main:app --reload
You'll see some output and the line:
Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Open up a browser and enter http://localhost:8000 for the URL.
You should see our return value, {"message":"Hello World"}
, and that means that we are successful!
In the next article, we'll explore FastAPI more and build out the information for our routes. Thanks for reading!