Olli
Olli

Reputation: 1126

Getting data from a FastAPI endpoint to a svelte frontend app

I am trying to build a simple app with Svelte to learn.

in my FastAPI backend (main.py) I simply have an endpoint hello:

@app.get("/hello")
async def hello():
    return "Hello"

I have the middlewares set up like this so requests from svelte should be allowed:

origins = [
    "http://localhost:5173",
    "localhost:5173"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

In the svelte app I have:

function getHello()
  {
    fetch("hello").then(d => d.text);
  }

console.log("the hello message", getHello());

but I get:

the hello message undefined

I have tried this with a similar template I have from reacts useQuery which seems to work. I am thinking I might be setting up the folders wrong.

FastAPI is in /backend

and the svelte app is in /my-app/src just from the basic tutorial installation.

Any pointers and tips on things to try and get this set up is greatly appreciated

Upvotes: 0

Views: 2991

Answers (1)

brunnerh
brunnerh

Reputation: 184607

The code you use to fetch the data cannot work like this.

  • The function returns nothing
  • The calling code (inside the log) does not account for it being asynchronous

(Also, the path 'hello' is relative, so this will only work with the correct site path in the browser.)

If the path is correct and the server works, the code should look more like this:

function getHello() {
    return fetch("hello").then(d => d.text);
}

getHello().then(text => console.log("the hello message", text));

Alternative async functions could be used or Svelte's {#await} directive.

(async () => {
  console.log("the hello message", await getHello()));
})();
{#await getHello() then text}
  {text}
{/await}

Upvotes: 2

Related Questions