FastAPI
Sharing application data through HTTP and WebSocket communications.
Our application works entirely within the browser. Open it in two tabs and create a poll in one. The other tab knows nothing about it. Reloading the page loses everything.
We will now move shared data to the server and explore:
- HTTP endpoints and request parameters
- Sending JSON data between JavaScript and Python
- Persistent WebSocket connections
- Broadcasting changes to connected browsers
1. HTTP endpoints
Open backend/poll_box/app.py. This is where our FastAPI application and its HTTP endpoints are defined.
The generated application already contains a health check endpoint. The @app.get decorator associates a URL path with a function that handles HTTP GET requests.
Letโs modify the function to accept a query parameter and do something with its value:
@app.get("/api/health")
async def health_check(source: str = "unknown"):
print(f"Health check from {source}")
return {"status": "ok", "reversed": source[::-1]}
FastAPI automatically passes the query parameter source to our function and converts the returned dictionary into a JSON response.
Visit http://localhost:3200/api/health?source=Hello in your browser. You should see:
{"status":"ok","reversed":"olleH"}
Meanwhile, the devserver terminal displays our printed message. Since the script also checks this endpoint to find when the backend is running, youโll see one from devserver.py whenever you restart the server.
Use
fastapi-vue-setup --health= .if you ever wish to disable the check on devserver startup, in case youโd like to remove this endpoint completely.
FastAPI also generates interactive API documentation from our endpoint definitions. Visit http://localhost:3200/docs to explore and experiment with our API.
2. Sharing data between users
In Part 2, we used Pinia to share data between Vue components. However, each browser runs its own instance of the application and has its own store. How can we make a poll created in one browser available to everyone?
Keeping state on the server
Unlike our frontend, FastAPI runs in a shared process that serves requests from all browsers. A module-level variable in Python is therefore a convenient place to keep shared application data.
Add an initially empty collection in app.py, below the application definition:
polls = {}
Every request handler in our server process can access and modify this same dictionary. Its contents remain available between requests, but are lost when the server restarts.
Receiving polls
Our Vue application already knows how to construct a poll and generate its UUID. We just need a way to send it to the server.
While GET requests retrieve data, we can use POST requests to submit data. Import UUID from uuid and HTTPException from fastapi, then add an endpoint before the final frontend.route() call:
@app.post("/api/polls/{poll_id}", status_code=201)
async def create_poll(poll_id: UUID, poll: dict):
id = str(poll_id)
if id in polls:
raise HTTPException(409, "Poll already exists")
polls[id] = poll
print("Created poll:", id, poll)
return {"id": id}
FastAPI reads the UUID from the URL and the poll from the JSON request body, based on the parameter names and types. An invalid UUID is rejected automatically.
For now, we store the received poll as it is. We will introduce more thorough data validation in Part 4.
Sending polls from the browser
Our createPoll action in polls.ts currently places each new poll directly into the Pinia store. Instead, we want to send it to our new endpoint and let the server store it.
Change the action declaration to:
async createPoll() {
Instead of assigning the poll directly to this.polls, create two local variables:
const id = crypto.randomUUID()
const poll = {
Keep the contents of the poll object unchanged.
After constructing the poll, but before clearing the editor, add:
const response = await fetch(`/api/polls/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(poll),
})
if (!response.ok) throw new Error('Could not create poll')
The browserโs fetch function sends our poll as JSON to FastAPI. Using async and await allows us to wait for the request to succeed before clearing the editor.
Similarly, in PollForm.vue, we need to wait for the action to complete before navigating back to the home page:
async function submit() {
if (await polls.createPoll()) {
router.push('/')
}
}
Try creating a poll and observe the devserver terminal. Our Python function receives and stores the poll.
Something is missing, though. Returning to the home page, we no longer see the poll we just created. The data now lives on the server, but our browsers have no way of knowing what is there or when it changes.
3. WebSocket connections
Our polls now live on the server, but the browsers still know nothing about them. We could provide an HTTP endpoint for retrieving the polls, but how would a browser know when someone has created a new one? In typical REST APIs the client makes a request and the server responds immediately. Barring long poll hacks, there is no way for the browser to send an update.
A WebSocket allows us to establish a connection that stays open, over which both sides can send messages whenever they need to. And that still runs conveniently over HTTP on the same server.
Connecting to the server
We want each browser to receive the current collection of polls as soon as it connects. We also need to keep track of these connections so we can send further updates.
Import WebSocket and WebSocketDisconnect from fastapi. Alongside our polls dictionary, define a set of connected clients:
clients: set[WebSocket] = set()
Add a WebSocket endpoint:
@app.websocket("/api/ws")
async def poll_updates(ws: WebSocket):
await ws.accept()
clients.add(ws)
try:
await ws.send_json(polls)
while True:
msg = await ws.receive_json()
print("Received:", msg)
except WebSocketDisconnect:
pass
finally:
clients.discard(ws)
Unlike an HTTP handler, a WebSocket handler continues running throughout the connection. Each connection has its own local variables, while our global variables are shared across all connections.
For now, we send the collection of polls and simply print any messages we receive from the browser, not yet sending any messages from client.
Broadcasting changes
Whenever someone creates a poll, we want to send the updated collection to everyone currently connected. Sending a message to multiple clients is called broadcasting.
Since we already keep track of our connections, we can write a reusable function for this purpose:
async def broadcast(msg):
for ws in list(clients):
try:
await ws.send_json(msg)
except (RuntimeError, WebSocketDisconnect):
clients.discard(ws)
All that remains is to trigger a broadcast whenever our collection changes. In create_poll, after storing the new poll and before returning the HTTP response, add:
await broadcast(polls)
Whether a browser has just connected or someone has created a new poll, it receives the entire collection in exactly the same format. This makes keeping our Pinia store up to date particularly simple.
4. Connecting Vue to live data
Our existing Vue components already know how to display polls from Pinia. We only need to connect the store to our WebSocket.
In polls.ts, declare a variable above the store definition:
let socket: WebSocket | undefined
The connection itself is a browser resource rather than application data, so we keep it outside the reactive state.
Add two actions to the store:
connect() {
socket = new WebSocket('/api/ws')
socket.onmessage = event => {
this.polls = JSON.parse(event.data)
}
},
disconnect() {
socket?.close()
socket = undefined
},
Whenever a message arrives, we decode its JSON and replace the collection in our store. Vue automatically updates all components displaying the polls.
We want the connection to remain open while navigating between pages, so we establish it in our root component, App.vue.
Add the following to its script section:
import { onMounted, onUnmounted } from 'vue'
import { usePollsStore } from './stores/polls'
const polls = usePollsStore()
onMounted(() => polls.connect())
onUnmounted(() => polls.disconnect())
These are Vueโs lifecycle hooks. They allow us to establish the connection when the application is mounted and close it when the application is removed.
We have not yet implemented voting on the server. To avoid modifying our local copy of shared data, replace the @click attribute on the answer buttons in PollCard.vue with disabled for now.
Testing our shared application
Open two browser windows side by side and create a poll in one of them. The new poll should appear immediately in both.
Try creating polls in either window, navigating to individual polls and opening their URLs in another browser.
Unlike our browser-only application, reloading the page no longer loses the polls. Restart the devserver, however, and they disappear: our Python dictionary only exists in memory.
Where we are now
REST is a good choice for independent operations that have a clear request and response. WebSockets are better suited to ongoing interactions where messages depend on earlier ones. Unlike separate HTTP requests, messages sent over a single WebSocket arrive in order, making it natural to send an initial state followed by updates without having to reconcile data arriving through separate requests. Combining REST for independent operations with WebSockets for synchronized state is often a good solution.
FastAPI now manages our shared application data. We use REST API to submit new polls and WebSockets to keep every connected browser synchronized. We have left the voting functionality for the next part, where we can do it with proper data structures rather than the plain polls: dict we have here.