FastAPI is a modern, high-performance Python web framework built on top of the Pydantic data validation library. It’s designed to be fast, easy to use, and efficient. In this guide, we’ll walk you through the process of creating your first FastAPI application. By the end, you’ll have a solid understanding of the framework’s core concepts and be able to build your own web APIs.
Prerequisites
Before we dive into the code, make sure you have the following:
- Python 3.7 or later installed on your system.
- FastAPI installed using pip:
pip install fastapi
- uvicorn installed for running the application:
pip install uvicorn
Creating a Basic FastAPI Application
1. Import Necessary Modules:
Python
from fastapi import FastAPI
2. Create a FastAPI Instance:
Python
app = FastAPI()
3. Define a Path Operation:
Python
@app.get("/") def read_root(): return {"Hello": "World"}
4. Run the Application:
Python
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
Explanation:
- The
FastAPI
instance is created, which forms the core of your application. - The
@app.get("/")
decorator defines a path operation. This means that when a GET request is made to the root path (http://127.0.0.1:8000), theread_root
function will be executed. - The
read_root
function returns a dictionary containing the message “Hello”: “World”. - Finally, the
uvicorn.run()
function is used to start the FastAPI application on the specified host and port.
Testing the Application
- Open a terminal or command prompt.
- Navigate to the directory where your Python file is located.
- Run the following command:
uvicorn main:app --reload
(replacemain
with the name of your Python file) - Open a web browser and go to http://127.0.0.1:8000. You should see the message “Hello: World” displayed.