In this tutorial, we will learn how to set up a new FastAPI project for a static website using the FastAPI web framework in Python. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
Step 1: Install FastAPI and Uvicorn
First, we need to install FastAPI and Uvicorn, an ASGI server that allows you to run FastAPI applications. Open your terminal and run the following commands:
pip install fastapi
pip install uvicorn
Step 2: Create a new directory for your project
Next, create a new directory for your FastAPI project. You can do this by running the following command in your terminal:
mkdir my_fastapi_project
cd my_fastapi_project
Step 3: Set up your project structure
Inside your project directory, create a new directory for your static website files. You can name this directory static
or public
. Within this directory, you can add your HTML, CSS, JavaScript, and other static files for your website.
mkdir static
Step 4: Create a main.py file
Now, create a new Python file named main.py
in your project directory. This file will contain the FastAPI application code. You can do this by running the following command:
touch main.py
Step 5: Write your FastAPI application code
Open the main.py
file in your favorite code editor and add the following code to set up a basic FastAPI application that serves your static website files:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# Serve the static website files
app.mount("/", StaticFiles(directory="static"), name="static")
# Define a route to serve the index.html file
@app.get("/", response_class=HTMLResponse)
async def read_root():
return FileResponse("static/index.html")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Step 6: Run your FastAPI application
To run your FastAPI application, go back to your terminal and run the following command:
uvicorn main:app --reload
This will start the Uvicorn ASGI server and run your FastAPI application. You should see output indicating that the server is running and serving your static website files.
Step 7: Access your website
Open your web browser and navigate to http://localhost:8000/
to access your static website served by the FastAPI application. You should see your website displayed in the browser.
That’s it! You have successfully set up a new FastAPI project for a static website. You can now further customize your website by adding more HTML, CSS, and JavaScript files to the static
directory and updating your FastAPI application code as needed.
I hope this tutorial was helpful in getting you started with FastAPI for building static websites. Enjoy building your projects with FastAPI and Python!