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:
- runs vite on watch mode so that the changes you perform on the Vue code are reflected by the vite server.
- also runs fastapi with hot reload so that changes on the code are picked up and served by uvicorn.
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!