OriginalStefikO / fastapi-svelte-starter

This is a tutorial and template on how to combine FastAPI with Svelte

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Important

1Q2024 update
Setup in Main branch is currently outdated, it worked for svelte 3, but there is an update to svelte 4 branch. It works with static router and prerendering (also trailing slash enabled for FastAPI). Sadly I don't have time to create the tutorial for it (like for the last version) right now, as i'm approaching the end of High school. So I won't push to main yet

In July when I have time again, there will probably be Svelte 5 and I'm not thinking of leaving svelte behind at all, so update will probably arrive. Thanks for your time and support.

Buy Me A Coffee

How to setup Fastapi with Svelte

Installation without custom setup:

Click here to expand
  1. Clone this repository
git clone https://github.com/OriginalStefikO/fastapi-svelte-starter.git .
  1. Create Python virtual enviroment (further just venv)(optional, but will prevent some unexpected errors)
    • when you restart your workspace you will need to activate it again, just run the second line

first we create venv from our python installation

~\AppData\Local\Programs\Python\Python311\python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt #Here are just

after that we activate it and install needed dependencies

  1. Get all svelte packages
cd ./frontend
npm install
cd ../
  1. Build svelte and run fastapi with uvicorn
cd ./frontend
npm run build; cd ../
uvicorn main:app --reload
  1. When developing in Svelte, you can use dev server
npm run dev

My way of setting up Fastapi + Svelte Hello world (1Q2023)

How to setup FasAPI with Svelte using Vite

This repo is just me trying to setup Fastapi with Svelte, I'm no expert and I just started, I just did't find any updated tutorials for this, so I made my own.

Setting up Fastapi

  1. Create Python Virtual Enviroment (further just venv)
    • this will make our life easier
    • when you restart your workspace you will need to activate it again, just run the second line

first we create venv from our python installation

~\AppData\Local\Programs\Python\Python311\python -m venv venv

venv\Scripts\activate

after that we activate it

  1. Create main.py
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
 
app = FastAPI()

# Define our static folder, where will be our svelte build later
app.mount("/assets", StaticFiles(directory="public/assets"), name="static")

# Simply the root will return our Svelte build
@app.get("/", response_class=FileResponse)
async def main():
    return "public/index.html"
  1. Download dependencies
    • Make sure your venv is activate, if not activate it
    • it may ask you to install autopep8, type yes
pip install fastapi
pip install "uvicorn[standard]"
  1. Run the Fastapi with uvicorn (not now, it won't work, we are missing frontend)
uvicorn main:app --reload

Setting up Svelte with Vite

  1. Start by initializing Vite:
    • Choose the following options:
    • Package name: frontend
    • Install packages: yes
    • Template: Svelte
    • Typescript: TS I recommend typescript, you won't hate your life later haha
npm init vite;
cd frontend;
npm install
  1. Now it still won't work, we need to edit config first
    • find vite.config.ts
    • I made two scripts, the easy one and the better one, the second will make your life easier I think
export default defineConfig({
   plugins: [svelte()],
   base: './',
   build: { 
      outDir: '../public',
      assetsDir: 'assets',
      emptyOutDir: true,
   },
})
export default defineConfig({
   plugins: [svelte()],
   base: "./", // This will make paths relative
   build: {
      emptyOutDir: true,
      outDir: '../public', // Where we want to put the build
      assetsDir: 'assets', // This will be folder inside the public
      rollupOptions: {
         input: {
            main: './index.html', // This index.html will be in public folder
            // if you have more pages, just add them bellow like this:
            // example: './pages/example.html',
         },
         output: {
            entryFileNames: 'assets/js/[name]-[hash].js', // Here we put all js files into js folder
            chunkFileNames: 'assets/js/[name]-[hash].js',
            // But after that we need to define which files should go where with regex
            assetFileNames: ({ name }) => {
               if (/\.(gif|jpe?g|png|svg)$/.test(name ?? '')) {
                  return 'assets/images/[name].[ext]';
               }

               if (/\.css$/.test(name ?? '')) {
                  return 'assets/css/[name]-[hash].[ext]';
               }

               return 'assets/[name]-[hash].[ext]';
            },
         }
      }     
   }
})

When we build our app now, it will build it to "public" folder and the files should be in their correct subfolders


When you want to run or build svelte, just run one of those in ./frontend

npm run dev
npm run build

and as I said before, to run fastapi, run

uvicorn main:app --reload

That's it! You should now have a fully functional application with a FastAPI backend and Svelte frontend. Of course, this is just a starting point and you can customize and add to it as needed for your own projects.

About

This is a tutorial and template on how to combine FastAPI with Svelte


Languages

Language:Svelte 24.7%Language:CSS 24.2%Language:TypeScript 22.4%Language:HTML 13.8%Language:Python 10.7%Language:JavaScript 4.2%