'Fastapi returns 404 when accessing URL in the browser

I am learning fastapi and created the sample following application

from fastapi import FastAPI
import uvicorn
app = FastAPI()

@app.get("/hello")
async def hello_world():
   return {"message": "hello_world"}

if __name__== "__main__":
   uvicorn.run(app, host="127.0.0.1", port=8080)

The server starts fine but when I test the url in browser I am getting the following error:

{"detail": "Not Found"}

and this error in the log:

"GET / HTTP /" 404 Not Found

I noticed another weird problem, when I make some error its not detecting the error and still starting the server. For example if I change the function like the following

@app.get("/hello")
async def hello_world():
   print (sample)
   return {"message": "hello_world"}

It should have thrown the error NameError: "sample" not defined but it still is starting the server. Any suggestions will be helpful



Solution 1:[1]

Question 1: Of course it doesn't work. You code a handler for path /hello. But you are testing path / which is not configured.

Question 2: You didn't define the variable sample.

Solution 2:[2]

always add the trailing slash after the path, had the same issue, took me hours to debug

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris
Solution 2 Otobong Jerome