Svelte +FastAPI ‘hello world’

Phil Harper
2 min readNov 17, 2020

--

Here’s a very quick (and probably bad) guide on how to integrate FastAPI with a Svelete front end. Ideally you’d entirely separate the two, with Svelte served independently of Fast API, but if you’re like me and you want a less than perfect but easier to manage solution, maybe this is it.

I wanted to use Svelte as the front end to either Flask, or Fast API. I tried a few ways to do it and found a setup that serves Svelte using FastAPI (actually starlette’s) StaticFiles in html mode.

  1. Setup a very basic Hello World with Fast API — return a random number which we’ll later display in Svelte. I called mine `main.py`
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.responses import RedirectResponse
import random
app = FastAPI()@app.get("/rand")
async def rand():
return random.randint(0, 100)

2) Create a folder inside your FastAPI project for Svelte, I called mine ‘front’. Then git clone the svelte template into that folder. When you’re done, you’ll need to call `npm install` inside your svelte app directory, you can then check it works with `npm run dev`. Here’s the directory tree:

3) In main.py we’re going to statically serve the `front` and ‘front/build’ directories, then redirect all root requests to that new static `front` endpoint. In main.py, add the following:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.responses import RedirectResponse
import random
app = FastAPI()app.mount("/front", StaticFiles(directory="front/public", html=True), name="front")
app.mount("/build", StaticFiles(directory="front/public/build"), name="build")
@app.get("/rand")
async def hello():
return random.randint(0, 100)
@app.get('/')
async def front():
return RedirectResponse(url='front')

4) Lets add a function to our Svelte app which calls the /rand endpoint we made and gets a random number from our FastAPI and displays it.

<script>let rand = -1;function getRand() {fetch("../rand").then(d => d.text()).then(d => (rand = d));}</script><main><h1>Hello {rand}!</h1><button on:click={getRand}>Get a random number</button></main>

5) You need to build you Svelte app on each change — as its being served via FastAPI. Type `npm run build inside front directory.

6) Check out your app — it should work

There are certainly better ways of doing this — in Flask it’s easier to setup using serve from directory. This was inspired by a post here

--

--

Phil Harper
Phil Harper

Written by Phil Harper

Formerly @truthloader. Sometimes @bbc. Running IMRGE VR. Creator of ‘Reddit for Sale’ and @howyougotcaughtinthenet Filmmaker. Creator. Programmer.

No responses yet