0

when I use below source

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

answer = "APPLE"

@app.get("/answer")
def get_answer():
  return answer

app.mount("/static", StaticFiles(directory="static", html=True), name="static")

then I can get API response "APPLE" but in "/" path, my html page is not found (404 error) So when I use below source

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

answer = "APPLE"

@app.get("/answer")
def get_answer():
  return answer

app.mount("/", StaticFiles(directory="static", html=True), name="static")

then I can get my page but not api response.

my path is like this enter image description here

  1. port change
  2. port shut down and reload
  3. move js file to static folder
kmyz
  • 1
  • is **main.py** inside **static** folder? – deadshot Jul 01 '23 at 06:18
  • @deadshot no main.py file is inside root folder and there is html, js, css etc is inside static folder! should I move main.py file in static folder? – kmyz Jul 01 '23 at 06:24
  • it’s because you don’t have `localhost:8000/` route. You have `localhost:8000/answer` only. If you want to get APPLE on `localhost:8000/`, change `@app.get("/answer”)` to `@app.get("/“)` – Artem Strogin Jul 01 '23 at 06:33
  • @ArtemStrogin ah, I don't want to get an answer from root path, but I want to open an HTML file, what should I do? – kmyz Jul 01 '23 at 06:41
  • What I want to do is when I access "/", the index.html file opens and when I fetch "/answer" from the js on that page, I want to get the answer as the return value. – kmyz Jul 01 '23 at 06:43
  • you need to create a function for `@app.get("/“)` that will render template (https://fastapi.tiangolo.com/advanced/templates/) – Artem Strogin Jul 01 '23 at 06:53
  • In addition to [this answer](https://stackoverflow.com/a/73113792/17865804), please have a look [here](https://stackoverflow.com/a/74498663/17865804) as well. – Chris Jul 01 '23 at 09:44

0 Answers0