Running the application
In the journey of building your first FastAPI application, running the application is a crucial step. This tutorial will guide you through the process in a beginner-friendly manner. We will use a simple FastAPI application for this demonstration.
Step 1: Installation
Before you start running your FastAPI application, ensure you have FastAPI installed. If not, install FastAPI and its server ASGI, uvicorn.
pip install fastapi uvicorn
Step2: Create A Simple FastAPI Application
Let's create a basic FastAPI application. Create a new file named main.py
and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
This code creates a new FastAPI application and defines a route ("/") that accepts GET requests. When a GET request is made to this route, the read_root
function is called and returns a JSON response {"Hello": "World"}
.
Step 3: Running the Application
To run the FastAPI application, we use uvicorn, a lightning-fast ASGI server. We specify the name of the file (without the extension) and the FastAPI application instance. In our case, the instance is app
.
In your terminal, navigate to the directory containing your main.py
file and execute the following command:
uvicorn main:app --reload
Here, main:app
tells uvicorn where to find the FastAPI application instance, and --reload
enables hot reloading, which means the server will automatically update whenever you make changes to your code.
After running this command, you should see output indicating that the server is running. By default, it will be hosted locally at http://127.0.0.1:8000
.
Step 4: Accessing the Application
To access your application, open a web browser and go to http://127.0.0.1:8000
. You should see the response from your root route, {"Hello": "World"}
.
Step 5: Shutting Down the Server
To stop the FastAPI server, go to your terminal and press CTRL+C
.
Conclusion
Congratulations! You've successfully run your first FastAPI application. Remember, the steps are simple: define your application and routes, and use uvicorn to serve your application. Don't hesitate to experiment with different routes and server options to get a feel for what you can do with FastAPI.
In the next tutorial, we will dive deeper into routing and how to handle different types of HTTP requests. Stay tuned!