← Back to Blog

Flask + Svelte: minimal server, typed Svelte stores

·8 min read

Flask + Svelte is the combination for developers who want the absolute minimum on the server and prefer Svelte's reactive primitives on the client. The same createQuery / createMutation pattern from the FastAPI + Svelte example applies here; only the server changes.

Server

# server/main.py
from flask import Flask
from flask_cors import CORS
from pyrpc_core import rpc
from pyrpc_flask import mount_flask

app = Flask(__name__)
CORS(app, origins=["http://localhost:5173"])

@rpc.query
def greet(name: str = "World") -> dict:
    return {"message": f"Hello, {name}!"}

@rpc.query
def read_item(item_id: int, q: str = None) -> dict:
    return {"item_id": item_id, "q": q}

@rpc.mutation
def create_item(name: str, description: str = None) -> dict:
    return {"name": name, "description": description, "created": True}

mount_flask(app)

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)

Client

// src/lib/pyrpc.ts
import { createSvelteClient } from "@pyrpc/svelte"
import type { Types } from "@pyrpc/types"

export const api = createSvelteClient<Types>({
  baseUrl: import.meta.env.VITE_API_URL ?? "http://localhost:5000",
})
<!-- src/routes/+page.svelte -->
<script lang="ts">
  import { api } from "$lib/pyrpc"
  let name = ""
  const greeting = api.greet.createQuery()
  const item = api.read_item.createQuery(() => ({ item_id: 42, q: "test" }))
  const createItem = api.create_item.createMutation()
  function handleCreate() {
    $createItem.mutate({ name }); name = ""
  }
</script>

{#if $greeting.isPending}<p>Loading…</p>
{:else}<pre>{JSON.stringify($greeting.data)}</pre>{/if}
<pre>{JSON.stringify($item.data)}</pre>
<input bind:value={name} />
<button on:click={handleCreate} disabled={$createItem.isPending}>
  {$createItem.isPending ? "Creating…" : "Create"}
</button>
{#if $createItem.isSuccess}<pre>{JSON.stringify($createItem.data)}</pre>{/if}

Run it

cd server && uv add pyrpc-core[flask] && pyrpc dev --yes
cd client && npm install && npm run dev

Open http://localhost:5173. Full source at examples/flask-svelte.