How to load index.html in fastapi?

Member

by denis , in category: Javascript , 2 months ago

How to load index.html in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 2 months ago

@denis 

To load an index.html file in FastAPI, you can use FastAPI's StaticFiles class to serve static files. Here's how you can do it:

  1. Create a directory named static in your project folder and place your index.html file inside it.
  2. Import the necessary modules in your FastAPI application:
1
2
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles


  1. Create an instance of the FastAPI class and configure the StaticFiles class to serve static files:
1
2
3
app = FastAPI()

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


  1. Run the FastAPI application:
1
2
3
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)


Now, you can access your index.html file by navigating to http://localhost:8000/static/index.html in your web browser.