FastAPI Basics
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is built on top of Starlette for the web parts, and Pydantic for the data parts.
Here's a tutorial on how to develop a basic FastAPI application:
Prerequisites
- Python 3.7 or later
- pip
Step 1: Create a new project directory
Create a new directory for your project. For example:
mkdir my-project cd my-project
Step 2: Create a virtual environment
It is recommended to use a virtual environment to isolate your project's dependencies from the global Python installation.
To create a new virtual environment, run the following command:
python -m venv venv
This will create a new directory called "venv" in your project directory, which contains a new Python installation.
To activate the virtual environment, run the following command:
source venv/bin/activate
Your virtual environment is now activated, and your terminal prompt should reflect this.
Step 3: Install FastAPI and Uvicorn
FastAPI is a web framework, and Uvicorn is a production-grade ASGI server. We'll use Uvicorn to run our FastAPI application.
To install FastAPI and Uvicorn, run the following command:
pip install fastapi uvicorn
Step 4: Create a main script
Create a new file called "main.py" in your project directory. This will be the entry point for your application.
Add the following code to "main.py":
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root(): return {"Hello": "World"}
This code creates a new FastAPI app, and defines a simple endpoint that returns a JSON response.
Step 5: Run the application
To run the application, execute the following command:
uvicorn main:app --reload
This will start the Uvicorn ASGI server, and run your FastAPI app. You should see output similar to the following:
INFO: Started server process [1234]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
The server is now running and listening for incoming requests on http://127.0.0.1:8000.
To test the endpoint, open a web browser and visit http://127.0.0.1:8000/. You should see the following JSON response:
{"Hello": "World"}
Congratulations, you have just created and run your first FastAPI application!
Next steps
This is just a basic example of what you can do with FastAPI. To learn more, check out the official documentation at https://fastapi.tiangolo.com/. The documentation includes a tutorial, as well as detailed reference documentation for all the features of FastAPI.