How to build a Website with FastAPI


In this tutorial, I'm going to show you how to create a website using FastAPI + TailwindCSS! If you're a beginner developer, don't worry! Each of these technologies is well-documented and easy to learn.

For those of you who don't know, FastAPI is a Python web framework that allows very seamless templating, routing, and backend integrations. TailwindCSS is a "utility-first CSS framework for rapidly building custom user interfaces."

With just these tools alone(and a little bit of Alpine.js on the side), one can build a bespoke, modern, and responsive website with relative ease.

So without further ado - here's part 1 of the tutorial!

Getting FastAPI

Activate your virtual environment and install required packages. If you want to get really fancy you can use requirements.txt.

conda activate myenv
pip install fastapi
pip install uvicorn
pip install requests
pip install jinja2

Once you've got this covered, change to your project directory and create a main.py file. After you've created the file, you can open your code editor of choice and add the following code.

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory="templates")

async def home():
    data = {
         "page": "Home Page"
    return templates.TemplateResponse("page.html", 
    {"request": request, "data": data})  

Notice that we have Jinja2 included in the FastAPI package. Jinja will allow us to serve HTML to the client and pass python variables as well. You have to make sure to create both the directory and an html file (template/page.html).

    Welcome to FastAPI Starter.

Finally, you will want to run Uvicorn to launch your server.

uvicorn main:app --reload

By this point, you should be able to duplicate and scale different HTML content. If you want to dive deeper, I would highly recommend this guide.

If you're still really new to web development, stay tuned for part 2 where I'll talk about styling your page with TailwindCSS and deploying to Heroku. Make sure to subscribe to my mailing list in the footer.

Join the Conversation!


  • avatar



  • avatar

    Hello World


© 2022 All rights reserved. – Designed & Coded by Adam Jones