Set Up Python fast API

To start a project with FastAPI in Python, follow these steps:
1. Install Python & Dependencies
Make sure you have Python 3.7 or later installed. You can check your Python version with:
python --version
Create a virtual environment:
python -m venv .venvActivate the virtual environment:
On Windows:
.venv\Scripts\activateOn macOS/Linux:
source .venv/bin/activate
install them using pip:
pip install fastapi uvicorn

2. Create main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
4. Run the FastAPI Application
Now, you can run the FastAPI app using uvicorn. From your project directory, run:
uvicorn main:app --reload
main: This refers to the Python filemain.py(without the.pyextension).app: This is the FastAPI app instance.--reload: This flag enables auto-reloading during development, so the server restarts when you make changes to your code.
You should see output similar to this:
INFO: Will watch for changes in these directories: ['<your_project_directory>']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

5. Access the FastAPI App
Open a browser and go to:
http://127.0.0.1:8000
You should see a JSON response:
{
"message": "Hello, FastAPI!"
}
6. Explore the Documentation
FastAPI automatically generates interactive documentation for your API. To view it:
Swagger UI: Go to
http://127.0.0.1:8000/docsReDoc: Go to
http://127.0.0.1:8000/redoc
7. Add More Routes
You can add more endpoints (routes) to your app by defining more functions with FastAPI decorators. For example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
In this case, the endpoint /items/{item_id} will accept an item_id as a URL parameter, and an optional query parameter q.
8. Test Your API
You can test the new /items/{item_id} endpoint by navigating to:
http://127.0.0.1:8000/items/42?q=test
This should return:
{
"item_id": 42,
"q": "test"
}
10. Optional: Create a requirements.txt
To share the project with others, you can generate a requirements.txt file that lists all your dependencies:
pip freeze > requirements.txt
Others can install the dependencies by running:
pip install -r requirements.txt



