Build A Website With FastAPI: A Quick And Easy Guide
Build a Website with FastAPI: A Quick and Easy Guide
Hey guys! Ever wanted to build a website using Python but found the existing frameworks a bit too clunky or complicated? Well, let me introduce you to FastAPI! It’s a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. But don’t let the “API” part fool you – you can totally use it to build full-fledged websites! In this guide, I’ll walk you through the process of building a simple website with FastAPI, covering everything from setting up your project to serving HTML templates and static files. So, buckle up, and let’s dive in!
Table of Contents
Setting Up Your FastAPI Project
First things first, you’ll need to have Python installed on your system. I recommend using Python 3.8 or higher to take full advantage of FastAPI’s features. Once you have Python, you can install FastAPI and its dependencies using pip. Open your terminal or command prompt and run the following command:
pip install fastapi uvicorn
Here’s a breakdown of what each package does:
- FastAPI: This is the main framework we’ll be using to build our website.
- Uvicorn: This is an ASGI (Asynchronous Server Gateway Interface) server that we’ll use to run our FastAPI application. Think of it as the engine that powers our website.
Now that you have FastAPI installed, let’s create a new directory for our project. I’ll call mine
my-fastapi-website
, but you can name it whatever you like. Navigate into the directory using the
cd
command:
mkdir my-fastapi-website
cd my-fastapi-website
Inside this directory, create a new Python file called
main.py
. This will be the main entry point for our FastAPI application. Open
main.py
in your favorite text editor or IDE and let’s start coding!
Let’s start with a basic FastAPI application that returns a simple “Hello, World!” message. Add the following code to
main.py
:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello, World!"}
In this code, we’re importing the
FastAPI
class from the
fastapi
package. We then create an instance of the
FastAPI
class and assign it to the
app
variable. This
app
variable is what we’ll use to define our routes and handle requests.
The
@app.get("/")
decorator tells FastAPI that we want to handle GET requests to the root URL (“/”) with the
read_root
function. The
async
keyword indicates that this is an asynchronous function, which allows FastAPI to handle multiple requests concurrently. Finally, the
read_root
function simply returns a dictionary with a “message” key and a value of “Hello, World!”. FastAPI will automatically convert this dictionary to a JSON response.
To run this application, open your terminal or command prompt and navigate to the project directory. Then, run the following command:
uvicorn main:app --reload
Here’s what each part of this command does:
- uvicorn: This is the ASGI server we installed earlier.
-
main:app:
This tells Uvicorn to run the
appobject from themain.pyfile. - –reload: This tells Uvicorn to automatically reload the application whenever we make changes to the code. This is super useful for development because we don’t have to manually restart the server every time we make a change.
Once you run this command, you should see something like this in your terminal:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [xxxx] using StatReload
This means that your FastAPI application is running on
http://127.0.0.1:8000
. Open your web browser and go to that URL. You should see the following JSON response:
{"message": "Hello, World!"}
Congratulations! You’ve just created your first FastAPI application.
Serving HTML Templates
Okay, so returning JSON is cool and all, but what about serving actual HTML pages? That’s where Jinja2 templates come in. Jinja2 is a popular templating engine for Python that allows you to create dynamic HTML pages. To use Jinja2 with FastAPI, you’ll need to install the
jinja2
package:
pip install jinja2
Once you have Jinja2 installed, create a new directory called
templates
in your project directory. This is where we’ll store our HTML templates. Inside the
templates
directory, create a new file called
index.html
. Add the following code to
index.html
:
<!DOCTYPE html>
<html>
<head>
<title>My FastAPI Website</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
This is a simple HTML template that displays a greeting with a name. The
{{ name }}
part is a Jinja2 variable that will be replaced with the actual name when we render the template.
Now, let’s modify our
main.py
file to serve this template. Add the following code to
main.py
:
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "name": "World"})
Let’s break down this code:
-
We’re importing
Request,HTMLResponse, andJinja2Templatesfrom thefastapipackage. -
We’re creating a
Jinja2Templatesobject and telling it to look for templates in thetemplatesdirectory. -
We’re adding
response_class=HTMLResponseto the@app.get("/")decorator. This tells FastAPI that we want to return an HTML response instead of a JSON response. -
We’re modifying the
read_rootfunction to take aRequestobject as an argument. This is required byTemplateResponse. -
We’re using
templates.TemplateResponseto render theindex.htmltemplate. We’re passing a dictionary with therequestobject and thenamevariable to the template.
Now, restart your Uvicorn server. Open your web browser and go to
http://127.0.0.1:8000
. You should see the following HTML page:
<h1>Hello, World!</h1>
You can change the value of the
name
variable in the
read_root
function to change the greeting. For example, if you change it to
"John"
, you’ll see the following HTML page:
<h1>Hello, John!</h1>
Serving Static Files
Most websites need to serve static files like CSS stylesheets, JavaScript files, and images. FastAPI makes it easy to serve static files using the
StaticFiles
class. To use
StaticFiles
, you’ll need to install the
starlette
package (if you haven’t already; FastAPI depends on it):
pip install starlette
Create a new directory called
static
in your project directory. This is where we’ll store our static files. Inside the
static
directory, create a new file called
style.css
. Add the following code to
style.css
:
h1 {
color: blue;
}
This is a simple CSS stylesheet that changes the color of the
<h1>
tag to blue.
Now, let’s modify our
main.py
file to serve static files. Add the following code to
main.py
:
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "name": "World"})
Let’s break down this code:
-
We’re importing
StaticFilesfrom thefastapi.staticfilespackage. -
We’re using
app.mountto mount thestaticdirectory to the/staticURL. This tells FastAPI to serve static files from thestaticdirectory when a request is made to the/staticURL. -
The
name="static"argument gives the static files route a name, which we can use to generate URLs to static files in our templates.
Now, let’s modify our
index.html
file to use the
style.css
stylesheet. Add the following code to the
<head>
section of
index.html
:
<link rel="stylesheet" href="{{ url_for('static', path='/style.css') }}">
This code uses the
url_for
function to generate a URL to the
style.css
file. The
url_for
function takes the name of the route (in this case, “static”) and any keyword arguments that are needed to generate the URL (in this case,
path='/style.css'
).
Now, restart your Uvicorn server. Open your web browser and go to
http://127.0.0.1:8000
. You should see the following HTML page, with the
<h1>
tag colored blue:
<h1>Hello, World!</h1>
Conclusion
And that’s it! You’ve built a simple website with FastAPI, serving HTML templates and static files. This is just the beginning, of course. You can use FastAPI to build much more complex websites with features like user authentication, databases, and more. But hopefully, this guide has given you a good starting point for your FastAPI journey. Now go out there and build something awesome!
Remember to explore the FastAPI documentation for more in-depth information and advanced features. Happy coding, and see you in the next guide!