Compare commits
3 Commits
da5d7d1961
...
88ac98c62f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88ac98c62f | ||
|
|
22ed791ad4 | ||
|
|
bbaa4c99f1 |
@@ -1,12 +1,100 @@
|
|||||||
|
# FastAPI – Environment Setup
|
||||||
|
|
||||||
|
This document describes the initial setup required to prepare a Python environment for developing a FastAPI application.
|
||||||
|
The steps below ensure isolation, dependency management, and reproducibility across environments.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
Before starting, ensure the following are installed on your system:
|
||||||
|
|
||||||
|
* Python 3.8 or higher
|
||||||
|
* `pip` (Python package manager)
|
||||||
|
* `venv` module (included by default with most Python installations)
|
||||||
|
|
||||||
|
You can verify your Python version with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 --version
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1: Create a Virtual Environment
|
||||||
|
|
||||||
|
A virtual environment isolates project dependencies and prevents conflicts with system-wide Python packages.
|
||||||
|
|
||||||
|
From the project root directory, run:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
```
|
```
|
||||||
|
|
||||||
|
This command creates a `.venv` directory containing the isolated Python environment.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2: Activate the Virtual Environment
|
||||||
|
|
||||||
|
Activate the virtual environment before installing any dependencies.
|
||||||
|
|
||||||
|
### Linux / macOS
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source .venv/bin/activate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Windows (PowerShell)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv\Scripts\Activate.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
After activation, your shell prompt should indicate that the virtual environment is active.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3: Install FastAPI
|
||||||
|
|
||||||
|
With the virtual environment activated, install FastAPI using `pip`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install fastapi
|
pip install fastapi
|
||||||
```
|
```
|
||||||
|
|
||||||
|
This installs the FastAPI framework and its required dependencies.
|
||||||
|
|
||||||
|
> Note: In a real application, FastAPI is commonly used with an ASGI server such as `uvicorn`, which can be installed later if needed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4: Freeze Dependencies
|
||||||
|
|
||||||
|
To ensure reproducibility across environments (local, CI/CD, staging, production), export the installed dependencies to a requirements file:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip freeze > requirment.txt
|
pip freeze > requirement.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
|
This file should be committed to version control and used by deployment pipelines to install exact dependency versions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resulting Files
|
||||||
|
|
||||||
|
After completing the steps above, your project directory should include:
|
||||||
|
|
||||||
|
* `.venv/` – Python virtual environment (should not be committed to VCS)
|
||||||
|
* `requirement.txt` – Dependency lock file
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
* Always activate the virtual environment before working on the project
|
||||||
|
* Do not commit `.venv/` to source control
|
||||||
|
* Keep `requirement.txt` updated when adding or upgrading dependencies
|
||||||
|
* Use the same `requirement.txt` in CI/CD pipelines for consistent builds
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
# FastAPI – Simple Route Example
|
||||||
|
|
||||||
|
This document demonstrates how to create a basic FastAPI application with a single HTTP route and how to run it using `uvicorn`, which is the default and recommended ASGI server for FastAPI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Create a Simple FastAPI Application
|
||||||
|
|
||||||
|
Create a Python file named `main.py` and add the following content:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
@@ -6,16 +16,75 @@ app = FastAPI()
|
|||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def home_dir():
|
def home_dir():
|
||||||
return {"message": "Home Pag"}
|
return {"message": "Home Page"}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Explanation
|
||||||
|
|
||||||
|
* `FastAPI()` initializes the application instance.
|
||||||
|
* `@app.get("/")` registers an HTTP GET endpoint at the root path (`/`).
|
||||||
|
* The `home_dir` function is the request handler and returns a JSON response.
|
||||||
|
* FastAPI automatically handles JSON serialization and response headers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Running the Application
|
||||||
|
|
||||||
|
FastAPI applications are typically run using **uvicorn**, an ASGI server designed for high performance.
|
||||||
|
|
||||||
|
### Option 1: Run Using FastAPI CLI (Development Mode)
|
||||||
|
|
||||||
|
FastAPI provides a development-friendly CLI wrapper that uses `uvicorn` internally:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
fastapi dev main.py
|
fastapi dev main.py
|
||||||
```
|
```
|
||||||
use uvicorn as defualt runner
|
|
||||||
or
|
This command:
|
||||||
we can run with uvicorn command
|
|
||||||
|
* Starts the application in development mode
|
||||||
|
* Enables auto-reload on code changes
|
||||||
|
* Automatically binds to a local development interface
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Option 2: Run Directly with Uvicorn (Recommended)
|
||||||
|
|
||||||
|
For explicit control over runtime configuration, run the application directly with `uvicorn`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uvicorn main:app --reload --host 0.0.0.0 --port 1234
|
uvicorn main:app --reload --host 0.0.0.0 --port 1234
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Command Breakdown
|
||||||
|
|
||||||
|
* `main` → Python file name (without `.py`)
|
||||||
|
* `app` → FastAPI application instance
|
||||||
|
* `--reload` → Automatically reloads the server on code changes (development only)
|
||||||
|
* `--host 0.0.0.0` → Exposes the service on all network interfaces
|
||||||
|
* `--port 1234` → Custom application port
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Accessing the Application
|
||||||
|
|
||||||
|
Once running, the application will be available at:
|
||||||
|
|
||||||
|
* API Endpoint:
|
||||||
|
`http://localhost:1234/`
|
||||||
|
|
||||||
|
* Interactive API Docs (Swagger UI):
|
||||||
|
`http://localhost:1234/docs`
|
||||||
|
|
||||||
|
* Alternative API Docs (ReDoc):
|
||||||
|
`http://localhost:1234/redoc`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
* Use `--reload` only in development environments
|
||||||
|
* In production, run `uvicorn` behind a process manager (e.g., systemd, Docker, Kubernetes)
|
||||||
|
* Explicitly define host and port for containerized and cloud deployments
|
||||||
|
* Keep the application entry point (`main:app`) consistent across environments
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +1,169 @@
|
|||||||
```python
|
# FastAPI – GET Endpoints and JSON Responses
|
||||||
|
|
||||||
|
This document demonstrates how to define multiple **GET endpoints** in FastAPI, return JSON responses, and use **path parameters** to retrieve specific data from an in-memory dataset.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Example Application
|
||||||
|
|
||||||
|
Create or update `main.py` with the following content:
|
||||||
|
|
||||||
|
```python
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
users = [
|
users = [
|
||||||
{'name': 'abbas ' , 'age': '20'},
|
{"name": "abbas", "age": 20},
|
||||||
{'name': 'mmd ' , 'age': '37'},
|
{"name": "mmd", "age": 37},
|
||||||
{'name': 'asghar ' , 'age': '19'}
|
{"name": "asghar", "age": 19},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def root_dir:
|
def root_dir():
|
||||||
return {'message' , 'api is working'}
|
return {"message": "API is working"}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/users")
|
@app.get("/users")
|
||||||
def home_dir():
|
def get_users():
|
||||||
return users
|
return users
|
||||||
|
|
||||||
|
|
||||||
@app.get("/user/{name_input}")
|
@app.get("/user/{name_input}")
|
||||||
def read_item(name_input: str):
|
def get_user_by_name(name_input: str):
|
||||||
for item in users:
|
for item in users:
|
||||||
if item["name"] == name_input:
|
if item["name"] == name_input:
|
||||||
return {"information": item}
|
return {"information": item}
|
||||||
return {"message" , "not worked"}
|
return {"message": "User not found"}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Code Overview
|
||||||
|
|
||||||
|
### Application Initialization
|
||||||
|
|
||||||
|
```python
|
||||||
|
app = FastAPI()
|
||||||
|
```
|
||||||
|
|
||||||
|
Initializes the FastAPI application instance.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### In-Memory Data Store
|
||||||
|
|
||||||
|
```python
|
||||||
|
users = [
|
||||||
|
{"name": "abbas", "age": 20},
|
||||||
|
{"name": "mmd", "age": 37},
|
||||||
|
{"name": "asghar", "age": 19},
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
* Simulates a database using a Python list
|
||||||
|
* Each user is represented as a JSON-compatible dictionary
|
||||||
|
* Suitable for development and testing purposes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Defined Endpoints
|
||||||
|
|
||||||
|
### Root Endpoint
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "API is working"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Used as a health check or readiness probe.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Get All Users
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /users
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{"name": "abbas", "age": 20},
|
||||||
|
{"name": "mmd", "age": 37},
|
||||||
|
{"name": "asghar", "age": 19}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns the full list of users as JSON.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Get User by Name (Path Parameter)
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /user/{name_input}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example Request:**
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /user/abbas
|
||||||
|
```
|
||||||
|
|
||||||
|
**Successful Response:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"information": {
|
||||||
|
"name": "abbas",
|
||||||
|
"age": 20
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Failure Response:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"message": "User not found"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Path Parameters
|
||||||
|
|
||||||
|
* `name_input` is a dynamic path parameter
|
||||||
|
* Automatically validated and converted to `str` by FastAPI
|
||||||
|
* Used to filter data at runtime
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Running the Application
|
||||||
|
|
||||||
|
Use `uvicorn` to start the service:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
* Use structured JSON responses (`key: value`) instead of tuples
|
||||||
|
* Validate user input when moving beyond in-memory data
|
||||||
|
* Replace in-memory storage with a database for production
|
||||||
|
* Use proper HTTP status codes (`404`, `200`) in real-world APIs
|
||||||
|
* Separate routing, models, and business logic as the project grows
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user