How to Create a FastAPI App: Simple Steps to Get Started
To create a FastAPI app, first import
FastAPI from the fastapi package, then create an instance with app = FastAPI(). Define routes using decorators like @app.get() to handle HTTP requests and run the app with an ASGI server such as uvicorn.Syntax
Creating a FastAPI app involves these parts:
- Import FastAPI: Bring in the FastAPI class from the
fastapipackage. - Create app instance: Use
app = FastAPI()to start your app. - Define routes: Use decorators like
@app.get()or@app.post()to create endpoints that respond to HTTP requests. - Run the app: Use an ASGI server like
uvicornto serve your app.
python
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI!"}
Example
This example shows a complete FastAPI app that responds with a JSON message at the root URL /. It demonstrates how to create the app, define a GET route, and run it using uvicorn.
python
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI!"} # To run this app, save as main.py and run: # uvicorn main:app --reload
Output
{"message": "Hello, FastAPI!"}
Common Pitfalls
Common mistakes when creating a FastAPI app include:
- Not using
async deffor route functions, which can limit performance. - Forgetting to create the
FastAPI()instance before defining routes. - Running the app without an ASGI server like
uvicorn. - Using incorrect decorator syntax or missing the route path string.
python
from fastapi import FastAPI app = FastAPI() # Wrong: missing async, no parentheses in decorator # @app.get # def root(): # return {"msg": "Hi"} # Right: @app.get("/") async def root(): return {"msg": "Hi"}
Quick Reference
FastAPI app creation quick tips:
- Import
FastAPIand createapp = FastAPI(). - Use
@app.get("/path")or@app.post("/path")to define routes. - Define route functions as
async deffor best performance. - Run with
uvicorn main:app --reloadfor development.
Key Takeaways
Create a FastAPI app by importing FastAPI and instantiating it with app = FastAPI().
Define routes using decorators like @app.get() with async functions for better performance.
Run your FastAPI app using an ASGI server such as uvicorn for it to work.
Avoid missing parentheses in decorators and always specify route paths as strings.
Use uvicorn with --reload during development to see changes instantly.