Serve Vue from Fastapi in a breeze

If you don’t care about text and just want to go straight to the code, I’ll make your life easy, here you go github.com/dimmaski/fastapi-vue. This repo contains a very simple setup of Vue + Vite being served from a Fastapi endpoint.

Recently, I’ve been playing around with Vue 3, and was looking for a simple way to serve my static assets from inside Fastapi, without losing development efficiency. I’ll like to share my current setup with you.

CDN?

To CDN or not to CDN πŸ’­? Nowadays most of the SPA assets that your browser pulls come from CDNs. And that’s all fine if you need to scale globally, set up cache, control TTLs, etc. If you don’t have any of those requirements, why not simply serve your static assets from your API?

Setup from scratch

Setup Vue + Vite

First of all, build your vue app. I recommend using Vite for bootstrapping.

npm create vite@latest ui -- --template vue

Once the Vue code is generated, head to your package.json file, and add the vite build --watch command to the script’s configuration. Then make sure to run npm install and then npm run build.

Setup Fastapi

Make sure that you have the fastapi package installed.

# main.py
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount('/', StaticFiles(directory='../ui/dist', html=True))

Folder Structure

Your folder structure should look something like the following.

.
β”œβ”€β”€ api
β”‚Β Β  └── main.py
└── ui
    β”œβ”€β”€ dist
    β”œβ”€β”€ index.html
    β”œβ”€β”€ node_modules
    β”œβ”€β”€ package.json
    β”œβ”€β”€ package-lock.json
    β”œβ”€β”€ public
    β”œβ”€β”€ README.md
    β”œβ”€β”€ src
    └── vite.config.js

Serve locally with hot reload

For local development, you can simply run the command below, which:

npm run watch --prefix ui & uvicorn api/main:app --reload && fg

To cancel click Ctrl+C twice.

Info: If you want to learn how to deploy your FastAPI as a Lambda function take a look at this post.

πŸŒπŸΌβ€β™‚οΈ Keep kicking!

· vue, fastapi