Svelte +FastAPI ‘hello world’

  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)
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')
<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>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Phil Harper

Phil Harper

117 Followers

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