Part 3: Connecting Vue to FastAPI

In Part 2, we built a voting application that works entirely in the browser. We can create polls, cast votes and view the results. But can we use it to organize a vote between several people?

Open the application in two browser tabs. Create a poll in one and switch to the other. The new poll is nowhere to be found.

Pinia allows our Vue components to share state, but each browser tab runs its own instance of the application, with its own store. Even storing the polls in the browser’s local storage would not make them available to other users on other devices.

Our FastAPI server, on the other hand, is shared by all users of the application. What if we moved the polls there?

For now, we will work with a single example poll. In App.vue, temporarily remove <PollForm /> and its import, the editing form, and the Edit button. Unwrap the normal poll display from its <template v-else> wrapper. Keep the creation and editing actions in Pinia; we will reconnect their interface in Part 4.

This leaves only the poll question, voting form and results, so we can focus on communication rather than rebuilding every feature at once.

1. Retrieving data from the server

Let’s start by making our example poll available to the browser. In backend/voting_app/app.py, define a poll using the same structure that our frontend already understands:

poll = {
    "id": "demo",
    "question": "Where should we meet?",
    "options": [
        {"label": "Library", "votes": 0},
        {"label": "Community hall", "votes": 0},
    ],
}

The poll now exists on the server, but the browser has no way of accessing it. We need to provide a URL from which it can retrieve the data.

FastAPI lets us associate a Python function with an HTTP method and a URL. Below our existing routes, add:

@app.get("/api/polls")
async def list_polls():
    return [poll]

Visit http://localhost:3200/api/polls in the browser. You should see our poll represented as JSON. FastAPI automatically converts the returned Python list and dictionaries into a JSON response.

We have created an API endpoint: an address at which our application provides data rather than a web page. The GET method indicates that we are retrieving something, without changing it.

Loading the poll into Pinia

Our existing Vue components already know how to display polls from the Pinia store. We only need to change where the store gets its data.

Open the application and try the following in the browser’s developer console:

const response = await fetch('/api/polls')
await response.json()

The browser’s built-in fetch function makes an HTTP request. Reading the JSON response gives us ordinary JavaScript objects, even though the original data was defined in Python.

In frontend/src/stores/polls.js, add two actions to the existing actions object. One applies new poll data while preserving local selections; the other retrieves that data:

replacePolls(updated) {
  this.polls = updated

  for (const poll of updated) {
    if (!(poll.id in this.voteDrafts)) {
      this.voteDrafts[poll.id] = null
    }
  }
},

async loadPolls() {
  const response = await fetch('/api/polls')
  if (!response.ok) throw new Error('Could not load polls')

  this.replacePolls(await response.json())
},

We replace the shared poll data, but keep any existing local vote selections. As in Part 2, actions access state through this, and can call each other the same way. Options Store actions are automatically available on the polls instance used by our components.

We want to load the polls when our application starts. In App.vue, use Vue’s onMounted lifecycle hook with our existing Pinia store instance (polls):

import { onMounted } from 'vue'
onMounted(() => polls.loadPolls())

Reload both browser tabs. They should now display the same example poll without either of them having created it.

Both browsers retrieve JSON copies of the shared Python poll from the FastAPI GET endpoint

The server now owns the original poll, while each Pinia store owns a JSON copy received in its HTTP response.

2. Changing data through an HTTP API

Cast a vote in one tab and reload the other. Did the vote appear there?

Our frontend still increments the vote count directly in Pinia. Although the original poll came from the server, the browser only received a copy. Modifying that copy does not modify the Python object it came from.

We need an endpoint that registers a vote on the server instead. Unlike a GET request, this operation changes data, so we will use POST.

What information does the server need? Only the ID of the poll and the index of the selected option. We can put the poll ID in the URL path and pass the option as a query parameter.

Import HTTPException from fastapi and add another endpoint:

@app.post("/api/polls/{poll_id}/vote")
async def submit_vote(poll_id: str, option: int):
    if poll_id != poll["id"]:
        raise HTTPException(404, "Poll not found")

    if not 0 <= option < len(poll["options"]):
        raise HTTPException(422, "Invalid option")

    poll["options"][option]["votes"] += 1
    return poll

FastAPI extracts poll_id from the URL path. Since option is not part of the path, FastAPI expects it as a query parameter. The type annotation int tells FastAPI to convert it to an integer and reject invalid values.

Try casting a vote directly from the browser console:

await fetch('/api/polls/demo/vote?option=0', { method: 'POST' })

Visit /api/polls again. The vote count has changed on the server. Try an option index of 99 instead and inspect the failed response in the browser’s Network panel.

Our two endpoints form a small REST-style HTTP API. Each request contains the information required to perform its operation.

Connecting the voting form

Replace the existing submitVote action in the Pinia store. Instead of incrementing the local vote count, we send a request and use the poll returned by FastAPI:

async submitVote(poll) {
  if (this.votedPollIds.includes(poll.id)) return

  const option = this.voteDrafts[poll.id]
  if (option == null) return

  const response = await fetch(
    `/api/polls/${poll.id}/vote?option=${option}`,
    { method: 'POST' }
  )

  if (!response.ok) throw new Error('Voting failed')

  Object.assign(poll, await response.json())
  this.votedPollIds.push(poll.id)
},

Notice that we do not send the new vote count. We only tell the server which option we voted for. The server increments its own count, which may already include votes from other users.

There is also a small problem with how we display results. Previously, a poll could only have votes if we had voted ourselves. Now we may receive a poll that already has votes from other users.

In App.vue, replace the v-else on the results container with a separate condition:

<div v-if="poll.options.some(option => option.votes > 0)">

The voting form still depends on whether we have voted in this browser, but the results are now displayed whenever anyone has voted.

Open the application in two tabs. Cast a vote in one and reload the other. Both tabs should now display the same vote counts.

3. Receiving changes as they happen

Our application now supports multiple users, but there is still something inconvenient about using it. We need to reload the page to see votes cast by other people.

So far, all communication has been initiated by the browser: we send a request, and FastAPI sends a response. The server has no channel through which it can inform the browser about subsequent changes.

We could call loadPolls periodically to check whether anything has changed. This technique is called polling. However, we would keep making requests even when there were no new votes.

A WebSocket provides another approach. Instead of making a separate HTTP request for each operation, we establish a connection that remains open. Both sides can send messages whenever they need to.

HTTP uses independent request-response pairs, while a WebSocket stays open for an initial snapshot, votes and later server updates

Opening a WebSocket

Add WebSocket and WebSocketDisconnect to the imports from fastapi. Create a WebSocket endpoint alongside our HTTP endpoints:

@app.websocket("/api/ws")
async def poll_updates(websocket: WebSocket):
    await websocket.accept()

    try:
        await websocket.send_json({"polls": [poll]})

        while True:
            message = await websocket.receive_json()
            await websocket.send_json({"received": message})
    except WebSocketDisconnect:
        pass

Notice that this function does not return a response and finish. It remains running, waiting for messages from this particular browser. Every connected browser gets its own running instance of the handler.

Let’s experiment before integrating it into Vue. In the browser console:

const url = new URL('/api/ws', location.href)
url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'

const socket = new WebSocket(url)
socket.onmessage = event => console.log(JSON.parse(event.data))

Once the connection opens, the current poll should appear in the console, without us explicitly requesting it. Now try sending a message:

socket.send(JSON.stringify({ option: 0 }))

The server echoes the message back. We can exchange any number of messages over the same connection. Unlike our HTTP API, WebSocket messages have no GET or POST method; we define their meaning ourselves.

Close this experimental connection with socket.close() when finished.

Remembering a client’s vote

Our HTTP endpoint registers votes, but it doesn’t know whether the same client has already voted. The restriction in Pinia only affects the browser’s interface: calling the API directly can bypass it.

With a WebSocket, the server has a natural place to remember information about a particular connection: the local variables of its handler.

Let’s use a message such as { "option": 0 } to cast a vote. This time, instead of echoing the message, we will register the vote and remember that this connection has voted.

Replace the WebSocket handler:

@app.websocket("/api/ws")
async def poll_updates(websocket: WebSocket):
    await websocket.accept()
    voted = False

    try:
        await websocket.send_json({"polls": [poll]})

        while True:
            message = await websocket.receive_json()
            option = message.get("option") if isinstance(message, dict) else None

            if voted or type(option) is not int:
                continue
            if not 0 <= option < len(poll["options"]):
                continue

            poll["options"][option]["votes"] += 1
            voted = True
            await websocket.send_json({"polls": [poll], "voteAccepted": True})
    except WebSocketDisconnect:
        pass

Connect again using the browser console and send the same vote message twice. The first vote is accepted, but the second is ignored.

The variable poll is shared by everyone, while voted belongs to a single running handler. Two browsers can therefore each cast one vote over their respective connections.

Each browser has Pinia drafts and its own WebSocket handler voted variable, while both handlers share the FastAPI poll

For this demonstration we expect valid JSON messages, and simply ignore invalid option selections and duplicate votes. The restriction applies to a connection, not to an authenticated person.

We are moving voting entirely to WebSockets, so remove the HTTP submit_vote endpoint. Keep the GET /api/polls endpoint for inspecting the shared data.

Broadcasting the results

There is still a problem: our handler only sends the updated results to the browser that cast the vote. How can we reach the other connected browsers?

Each handler has access to its own WebSocket object. If we collect these objects in a shared set, we can send a message to every connected client.

Add the following alongside the shared poll variable:

from asyncio import Lock

clients: set[WebSocket] = set()
lock = Lock()

In the handler, register the connection and send the initial snapshot together. After accepting a vote, send the updated poll to all clients instead of just the sender:

@app.websocket("/api/ws")
async def poll_updates(websocket: WebSocket):
    await websocket.accept()
    voted = False

    try:
        async with lock:
            await websocket.send_json({"polls": [poll]})
            clients.add(websocket)

        while True:
            message = await websocket.receive_json()
            option = message.get("option") if isinstance(message, dict) else None

            if voted or type(option) is not int:
                continue
            if not 0 <= option < len(poll["options"]):
                continue

            async with lock:
                poll["options"][option]["votes"] += 1
                voted = True

                for client in tuple(clients):
                    try:
                        await client.send_json({
                            "polls": [poll],
                            "voteAccepted": client is websocket,
                        })
                    except (WebSocketDisconnect, OSError, RuntimeError):
                        clients.discard(client)
    except WebSocketDisconnect:
        pass
    finally:
        clients.discard(websocket)

Sending the same update to multiple clients is called broadcasting. The lock prevents two handlers from broadcasting simultaneously and ensures that new clients receive their initial snapshot in order with other updates. We remove closed connections from the set so we no longer try to send messages to them.

Everyone receives the same poll data, but only the client that cast the vote receives voteAccepted: true.

One vote updates the shared count and is broadcast to every browser, with acceptance sent only to the voting connection

Try opening WebSocket connections in the developer consoles of two browser tabs. Send a vote in one and observe the message arriving in both. Close the experimental connections before continuing.

4. Connecting Vue to the WebSocket

We already know how to open a WebSocket in JavaScript, and our Pinia store has an action called replacePolls for applying new poll data.

A WebSocket is a browser resource rather than serializable application data, so keep it in a module-level variable above defineStore, not in the store’s state:

let socket

Add connect and disconnect to the store’s actions object:

connect() {
  this.disconnect()
  this.votedPollIds = []

  const url = new URL('/api/ws', location.href)
  url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'

  const connection = new WebSocket(url)
  socket = connection

  connection.onmessage = event => {
    if (socket !== connection) return

    const message = JSON.parse(event.data)
    this.replacePolls(message.polls)

    if (message.voteAccepted) {
      this.votedPollIds.push(this.polls[0].id)
    }
  }
},

disconnect() {
  socket?.close()
  socket = undefined
},

The arrow callback retains the connect action’s this, allowing it to call replacePolls and update voting history on the store.

The server sends the initial poll as soon as the connection opens, so we no longer need loadPolls. Remove that action; the new Options Store actions are available to App.vue automatically.

In App.vue, replace our earlier onMounted call and import onUnmounted alongside onMounted:

onMounted(() => polls.connect())
onUnmounted(() => polls.disconnect())

Finally, change submitVote once more. We no longer need to wait for an HTTP response. We send a message over the open connection:

submitVote(poll) {
  if (this.votedPollIds.includes(poll.id)) return

  const option = this.voteDrafts[poll.id]
  if (option == null) return
  if (socket?.readyState !== WebSocket.OPEN) return

  socket.send(JSON.stringify({ option }))
},

We no longer update the vote count or record that we have voted here. We let the incoming message from the server do both. Since this version supports just one poll, the message handler uses the ID of that poll when recording an accepted vote.

Open the application in two browser tabs and cast a vote in each. Watch the results update in both tabs without reloading either of them.

Try selecting an option in one tab without submitting it, then cast a vote in the other. The results update, but the unfinished selection remains intact. Pinia is still managing our reactive interface and local interaction state; FastAPI now manages the shared application data.

Where we are now

We have explored two ways for a frontend to communicate with FastAPI:

  • HTTP endpoints: the browser makes individual requests to retrieve data or perform operations. Every request is independent of the previous one.
  • WebSockets: the browser and server maintain an open, two-way connection. The server can remember connection-specific state and push updates to clients without waiting for a request.

Our application now has three kinds of state: local interface state in Pinia, connection-specific state in the WebSocket handler, and shared poll data in FastAPI.

We have deliberately limited this chapter to a single poll. In Part 4, we will build on these communication mechanisms and complete the application.