├── .gitignore
├── Fast API Fundamentals
├── 01 FastAPI Basics
│ ├── 01 FastAPI Setup and First API
│ │ └── fastapi_setup.py
│ ├── 02 Basic Endpoints and Responses
│ │ └── basic_endpoints.py
│ ├── 03 Request Visualization
│ │ └── request_visualization.py
│ └── README.md
├── 02 API Development
│ ├── 01 Path and Query Parameters
│ │ └── path_query_parameters.py
│ ├── 02 Data Validation with Pydantic
│ │ └── data_validation_pydantic.py
│ ├── 03 Response Metrics Visualization
│ │ └── response_metrics_visualization.py
│ └── README.md
├── 03 Advanced FastAPI Features
│ ├── 01 Authentication and Authorization
│ │ └── authentication_authorization.py
│ ├── 02 Middleware and Async Programming
│ │ └── middleware_async.py
│ ├── 03 Performance Metrics Visualization
│ │ └── performance_metrics_visualization.py
│ └── README.md
├── 04 Testing and Documentation
│ ├── 01 Unit and Integration Testing
│ │ └── unit_integration_testing.py
│ ├── 02 Automatic API Documentation
│ │ └── automatic_api_documentation.py
│ ├── 03 Test Coverage Visualization
│ │ └── test_coverage_visualization.py
│ └── README.md
└── 05 Deployment and Scaling
│ ├── 01 Dockerizing FastAPI Apps
│ └── dockerizing_fastapi.py
│ ├── 02 Cloud Deployment (e.g., AWS, Heroku)
│ └── cloud_deployment.py
│ ├── 03 Scalability Metrics Visualization
│ └── scalability_metrics_visualization.py
│ └── README.md
├── Fast API Interview Questions
└── README.md
├── LICENSE
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
--------------------------------------------------------------------------------
/Fast API Fundamentals/01 FastAPI Basics/01 FastAPI Setup and First API/fastapi_setup.py:
--------------------------------------------------------------------------------
1 | # %% fastapi_setup.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI()
12 |
13 | # Root Endpoint
14 | @app.get("/")
15 | def read_root():
16 | return {"message": "Welcome to your first FastAPI application!"}
17 |
18 | # Function to test API setup
19 | def test_api_setup():
20 | print("Testing FastAPI Setup")
21 |
22 | # Track request success
23 | success_counts = {"Successful": 0, "Failed": 0}
24 |
25 | # Test root endpoint
26 | url = "http://localhost:8000/"
27 | try:
28 | response = requests.get(url)
29 | response.raise_for_status()
30 | success_counts["Successful"] += 1
31 | print(f"GET {url}: {response.status_code} - {response.json()}")
32 | except requests.RequestException as e:
33 | success_counts["Failed"] += 1
34 | print(f"Error for {url}: {e}")
35 |
36 | # Visualization
37 | plt.figure(figsize=(6, 4))
38 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
39 | plt.title("API Setup Request Success")
40 | plt.xlabel("Status")
41 | plt.ylabel("Count")
42 | plt.savefig("fastapi_setup_output.png")
43 | print("Visualization: Setup success saved as fastapi_setup_output.png")
44 |
45 | # Run FastAPI server in a thread
46 | def run_server():
47 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
48 |
49 | if __name__ == "__main__":
50 | # Start server in a separate thread
51 | server_thread = threading.Thread(target=run_server)
52 | server_thread.daemon = True
53 | server_thread.start()
54 |
55 | # Wait for server to start
56 | time.sleep(2)
57 |
58 | # Test API setup
59 | test_api_setup()
60 |
61 | # Keep the main thread alive briefly to view results
62 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/01 FastAPI Basics/02 Basic Endpoints and Responses/basic_endpoints.py:
--------------------------------------------------------------------------------
1 | # %% basic_endpoints.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI, HTTPException
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI()
12 |
13 | # Synthetic Data
14 | users = [
15 | {"id": 1, "name": "Alice", "email": "alice@example.com"},
16 | {"id": 2, "name": "Bob", "email": "bob@example.com"}
17 | ]
18 |
19 | # Endpoints
20 | @app.get("/users")
21 | def get_users():
22 | return users
23 |
24 | @app.get("/users/{user_id}")
25 | def get_user(user_id: int):
26 | for user in users:
27 | if user["id"] == user_id:
28 | return user
29 | raise HTTPException(status_code=404, detail="User not found")
30 |
31 | @app.post("/users")
32 | def create_user(user: dict):
33 | if "id" not in user or "name" not in user or "email" not in user:
34 | raise HTTPException(status_code=400, detail="Invalid user data")
35 | users.append(user)
36 | return user, 201
37 |
38 | # Function to test endpoints
39 | def test_endpoints():
40 | print("Synthetic Data: Users created")
41 | print(f"Users: {users}")
42 |
43 | # Track request success
44 | success_counts = {"Successful": 0, "Failed": 0}
45 |
46 | # Test endpoints
47 | endpoints = [
48 | ("GET", "http://localhost:8000/users"),
49 | ("GET", "http://localhost:8000/users/1"),
50 | ("GET", "http://localhost:8000/users/999")
51 | ]
52 |
53 | for method, url in endpoints:
54 | try:
55 | response = requests.get(url)
56 | response.raise_for_status()
57 | success_counts["Successful"] += 1
58 | print(f"{method} {url}: {response.status_code}")
59 | except requests.RequestException as e:
60 | success_counts["Failed"] += 1
61 | print(f"Error for {url}: {e}")
62 |
63 | # Test POST
64 | new_user = {"id": 3, "name": "Charlie", "email": "charlie@example.com"}
65 | try:
66 | response = requests.post("http://localhost:8000/users", json=new_user)
67 | response.raise_for_status()
68 | success_counts["Successful"] += 1
69 | print(f"POST /users: {response.status_code}")
70 | except requests.RequestException as e:
71 | success_counts["Failed"] += 1
72 | print(f"Error for POST /users: {e}")
73 |
74 | # Visualization
75 | plt.figure(figsize=(6, 4))
76 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
77 | plt.title("Endpoint Request Success")
78 | plt.xlabel("Status")
79 | plt.ylabel("Count")
80 | plt.savefig("basic_endpoints_output.png")
81 | print("Visualization: Endpoint success saved as basic_endpoints_output.png")
82 |
83 | # Run FastAPI server in a thread
84 | def run_server():
85 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
86 |
87 | if __name__ == "__main__":
88 | # Start server in a separate thread
89 | server_thread = threading.Thread(target=run_server)
90 | server_thread.daemon = True
91 | server_thread.start()
92 |
93 | # Wait for server to start
94 | time.sleep(2)
95 |
96 | # Test endpoints
97 | test_endpoints()
98 |
99 | # Keep the main thread alive briefly to view results
100 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/01 FastAPI Basics/03 Request Visualization/request_visualization.py:
--------------------------------------------------------------------------------
1 | # %% request_visualization.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI, HTTPException
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI()
12 |
13 | # Synthetic Data
14 | items = [
15 | {"id": 1, "name": "Laptop", "price": 999.99},
16 | {"id": 2, "name": "Phone", "price": 499.99}
17 | ]
18 |
19 | # Endpoints for testing
20 | @app.get("/items")
21 | def get_items():
22 | return items
23 |
24 | @app.get("/items/{item_id}")
25 | def get_item(item_id: int):
26 | for item in items:
27 | if item["id"] == item_id:
28 | return item
29 | raise HTTPException(status_code=404, detail="Item not found")
30 |
31 | @app.post("/items")
32 | def create_item(item: dict):
33 | if "id" not in item or "name" not in item or "price" not in item:
34 | raise HTTPException(status_code=400, detail="Invalid item data")
35 | items.append(item)
36 | return item, 201
37 |
38 | # Function to simulate and visualize requests
39 | def visualize_requests():
40 | print("Synthetic Data: Items created")
41 | print(f"Items: {items}")
42 |
43 | # Track request success
44 | success_counts = {"Successful": 0, "Failed": 0}
45 |
46 | # Simulate requests
47 | requests_list = [
48 | ("GET", "http://localhost:8000/items"),
49 | ("GET", "http://localhost:8000/items/1"),
50 | ("GET", "http://localhost:8000/items/999"),
51 | ("POST", "http://localhost:8000/items", {"id": 3, "name": "Tablet", "price": 299.99}),
52 | ("POST", "http://localhost:8000/items", {"name": "Invalid"}) # Invalid data
53 | ]
54 |
55 | for method, url, *data in requests_list:
56 | try:
57 | if method == "GET":
58 | response = requests.get(url)
59 | else:
60 | response = requests.post(url, json=data[0])
61 | response.raise_for_status()
62 | success_counts["Successful"] += 1
63 | print(f"{method} {url}: {response.status_code}")
64 | except requests.RequestException as e:
65 | success_counts["Failed"] += 1
66 | print(f"Error for {method} {url}: {e}")
67 |
68 | # Visualization
69 | plt.figure(figsize=(6, 4))
70 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
71 | plt.title("API Request Success Rates")
72 | plt.xlabel("Status")
73 | plt.ylabel("Count")
74 | plt.savefig("request_visualization_output.png")
75 | print("Visualization: Request success saved as request_visualization_output.png")
76 |
77 | # Run FastAPI server in a thread
78 | def run_server():
79 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
80 |
81 | if __name__ == "__main__":
82 | # Start server in a separate thread
83 | server_thread = threading.Thread(target=run_server)
84 | server_thread.daemon = True
85 | server_thread.start()
86 |
87 | # Wait for server to start
88 | time.sleep(2)
89 |
90 | # Simulate and visualize requests
91 | visualize_requests()
92 |
93 | # Keep the main thread alive briefly to view results
94 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/01 FastAPI Basics/README.md:
--------------------------------------------------------------------------------
1 | # 🚀 FastAPI Basics with Python Roadmap
2 |
3 |
9 | Your step-by-step guide to mastering FastAPI basics with Python, from setup to visualizing API requests, for building high-performance APIs and preparing for backend development interviews
10 |
11 | ---
12 |
13 | ## 📖 Introduction
14 |
15 | Welcome to the **FastAPI Basics with Python Roadmap**! 🚀 This roadmap is designed to teach you the fundamentals of FastAPI, a modern, high-performance web framework for building APIs with Python. It covers setting up your first FastAPI application, creating basic endpoints, and visualizing API requests. Aligned with the tech-driven era (May 3, 2025), this roadmap equips you with practical skills for backend development, AI/ML integration, and interview preparation for 6 LPA+ roles.
16 |
17 | ## 🌟 What’s Inside?
18 |
19 | - **FastAPI Setup and First API**: Installing FastAPI and creating your first endpoint.
20 | - **Basic Endpoints and Responses**: Building GET and POST endpoints with JSON responses.
21 | - **Request Visualization**: Monitoring and visualizing API request success rates.
22 | - **Hands-on Code**: Practical examples with Python scripts and visualizations.
23 | - **Interview Scenarios**: Key questions and answers for FastAPI basics.
24 |
25 | ## 🔍 Who Is This For?
26 |
27 | - Backend Developers starting with RESTful APIs in Python.
28 | - AI/ML Engineers integrating models with APIs.
29 | - Software Engineers learning modern web frameworks.
30 | - Anyone preparing for backend or AI/ML interviews.
31 |
32 | ## 🗺️ Learning Roadmap
33 |
34 | This roadmap covers three key areas of FastAPI basics:
35 |
36 | ### 🛠️ FastAPI Setup and First API
37 | - FastAPI Installation and Configuration
38 | - Creating Your First Endpoint
39 | - Accessing Swagger UI
40 |
41 | ### 📝 Basic Endpoints and Responses
42 | - GET and POST Endpoints
43 | - Handling JSON Responses and Status Codes
44 | - Basic Error Handling
45 |
46 | ### 📊 Request Visualization
47 | - Simulating API Requests
48 | - Visualizing Request Success Rates
49 | - Analyzing API Performance
50 |
51 | ## 💡 Why Master FastAPI Basics?
52 |
53 | FastAPI is a game-changer for API development:
54 | 1. **Performance**: Asynchronous capabilities for fast APIs.
55 | 2. **Ease of Use**: Intuitive syntax and automatic documentation.
56 | 3. **Scalability**: Ideal for small prototypes to large applications.
57 | 4. **Interview Relevance**: Tested in backend coding challenges.
58 |
59 | ## 📆 Study Plan
60 |
61 | - **Week 1**:
62 | - Day 1: FastAPI Setup and First API
63 | - Day 2: Basic Endpoints and Responses
64 | - Day 3: Request Visualization
65 | - Day 4-5: Review content and practice interview scenarios
66 | - Day 6-7: Build a small API combining all concepts
67 |
68 | ## 🛠️ Setup Instructions
69 |
70 | 1. **Python Environment**:
71 | - Install Python 3.8+ and pip.
72 | - Create a virtual environment: `python -m venv fastapi_env; source fastapi_env/bin/activate`.
73 | - Install dependencies: `pip install fastapi uvicorn requests matplotlib pandas`.
74 | 2. **Running FastAPI**:
75 | - Run a FastAPI app: `uvicorn main:app --reload`.
76 | - Access the app at `http://localhost:8000` and docs at `http://localhost:8000/docs`.
77 | 3. **Datasets**:
78 | - Uses synthetic data (e.g., user data, API requests).
79 | - Note: Code uses simulated data to avoid file I/O constraints.
80 | 4. **Running Code**:
81 | - Use VS Code, PyCharm, or Google Colab.
82 | - View outputs in terminal, browser (Swagger UI), and Matplotlib visualizations (PNGs).
83 | - Check terminal for errors; ensure dependencies are installed.
84 |
85 | ## 🏆 Practical Tasks
86 |
87 | 1. **FastAPI Setup and First API**:
88 | - Install FastAPI and create a root endpoint.
89 | - Test the endpoint using Swagger UI.
90 | 2. **Basic Endpoints and Responses**:
91 | - Create GET and POST endpoints for a user API.
92 | - Handle errors with HTTP status codes.
93 | 3. **Request Visualization**:
94 | - Simulate API requests and track success/failure.
95 | - Visualize request success rates.
96 |
97 | ## 💡 Interview Tips
98 |
99 | - **Common Questions**:
100 | - What is FastAPI, and why is it used?
101 | - How do you create a GET endpoint in FastAPI?
102 | - How does FastAPI handle JSON responses?
103 | - How do you test a FastAPI endpoint?
104 | - **Tips**:
105 | - Explain FastAPI setup with code (e.g., `@app.get`, `FastAPI()`).
106 | - Demonstrate endpoint creation and testing.
107 | - Code tasks like building a simple API or handling errors.
108 | - Discuss FastAPI’s automatic documentation feature.
109 | - **Coding Tasks**:
110 | - Create a FastAPI app with a GET endpoint.
111 | - Simulate API requests and handle errors.
112 | - **Conceptual Clarity**:
113 | - Explain FastAPI’s async capabilities.
114 | - Describe the role of Swagger UI in API development.
115 |
116 | ## 📚 Resources
117 |
118 | - [FastAPI Documentation](https://fastapi.tiangolo.com/)
119 | - [Uvicorn Documentation](https://www.uvicorn.org/)
120 | - [Python Requests Documentation](https://requests.readthedocs.io/)
121 | - [Matplotlib Documentation](https://matplotlib.org/stable/contents.html)
122 |
123 | ## 🤝 Contributions
124 |
125 | 1. Fork the repository.
126 | 2. Create a feature branch (`git checkout -b feature/fastapi-basics`).
127 | 3. Commit changes (`git commit -m 'Add FastAPI basics content'`).
128 | 4. Push to the branch (`git push origin feature/fastapi-basics`).
129 | 5. Open a Pull Request.
130 |
131 | ---
132 |
133 |
134 |
Happy Learning and Good Luck with Your Interviews! ✨
135 |
--------------------------------------------------------------------------------
/Fast API Fundamentals/02 API Development/01 Path and Query Parameters/path_query_parameters.py:
--------------------------------------------------------------------------------
1 | # %% path_query_parameters.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI()
12 |
13 | # Synthetic Data
14 | items = [
15 | {"id": 1, "name": "Laptop", "category": "Electronics", "price": 999.99},
16 | {"id": 2, "name": "Phone", "category": "Electronics", "price": 499.99},
17 | {"id": 3, "name": "Book", "category": "Stationery", "price": 19.99}
18 | ]
19 |
20 | # Endpoints
21 | @app.get("/items/{item_id}")
22 | def get_item(item_id: int):
23 | for item in items:
24 | if item["id"] == item_id:
25 | return item
26 | return {"error": "Item not found"}, 404
27 |
28 | @app.get("/items")
29 | def get_items_by_category(category: str = None, max_price: float = None):
30 | filtered_items = items
31 | if category:
32 | filtered_items = [item for item in filtered_items if item["category"].lower() == category.lower()]
33 | if max_price is not None:
34 | filtered_items = [item for item in filtered_items if item["price"] <= max_price]
35 | return filtered_items if filtered_items else {"error": "No items found"}, 404
36 |
37 | # Function to test path and query parameters
38 | def test_parameters():
39 | print("Synthetic Data: Items created")
40 | print(f"Items: {items}")
41 |
42 | # Track request success
43 | success_counts = {"Successful": 0, "Failed": 0}
44 |
45 | # Test endpoints
46 | endpoints = [
47 | ("GET", "http://localhost:8000/items/1"),
48 | ("GET", "http://localhost:8000/items/999"),
49 | ("GET", "http://localhost:8000/items?category=Electronics"),
50 | ("GET", "http://localhost:8000/items?category=Electronics&max_price=500.0"),
51 | ("GET", "http://localhost:8000/items?category=Unknown")
52 | ]
53 |
54 | for method, url in endpoints:
55 | try:
56 | response = requests.get(url)
57 | response.raise_for_status()
58 | success_counts["Successful"] += 1
59 | print(f"{method} {url}: {response.status_code}")
60 | except requests.RequestException as e:
61 | success_counts["Failed"] += 1
62 | print(f"Error for {method} {url}: {e}")
63 |
64 | # Visualization
65 | plt.figure(figsize=(6, 4))
66 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
67 | plt.title("Path and Query Parameter Request Success")
68 | plt.xlabel("Status")
69 | plt.ylabel("Count")
70 | plt.savefig("path_query_parameters_output.png")
71 | print("Visualization: Request success saved as path_query_parameters_output.png")
72 |
73 | # Run FastAPI server in a thread
74 | def run_server():
75 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
76 |
77 | if __name__ == "__main__":
78 | # Start server in a separate thread
79 | server_thread = threading.Thread(target=run_server)
80 | server_thread.daemon = True
81 | server_thread.start()
82 |
83 | # Wait for server to start
84 | time.sleep(2)
85 |
86 | # Test parameters
87 | test_parameters()
88 |
89 | # Keep the main thread alive briefly to view results
90 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/02 API Development/02 Data Validation with Pydantic/data_validation_pydantic.py:
--------------------------------------------------------------------------------
1 | # %% data_validation_pydantic.py
2 | # Setup: pip install fastapi uvicorn pydantic requests matplotlib pandas
3 | from fastapi import FastAPI
4 | from pydantic import BaseModel, EmailStr
5 | import uvicorn
6 | import requests
7 | import matplotlib.pyplot as plt
8 | from collections import Counter
9 | import threading
10 | import time
11 |
12 | app = FastAPI()
13 |
14 | # Pydantic Model
15 | class User(BaseModel):
16 | id: int
17 | name: str
18 | email: EmailStr
19 | age: int | None = None
20 |
21 | # Synthetic Data
22 | users = [
23 | {"id": 1, "name": "Alice", "email": "alice@example.com", "age": 30},
24 | {"id": 2, "name": "Bob", "email": "bob@example.com", "age": 25}
25 | ]
26 |
27 | # Endpoints
28 | @app.get("/users")
29 | def get_users():
30 | return users
31 |
32 | @app.post("/users")
33 | def create_user(user: User):
34 | users.append(user.dict())
35 | return user, 201
36 |
37 | # Function to test data validation
38 | def test_validation():
39 | print("Synthetic Data: Users created")
40 | print(f"Users: {users}")
41 |
42 | # Track request success
43 | success_counts = {"Successful": 0, "Failed": 0}
44 |
45 | # Test endpoints
46 | requests_list = [
47 | ("GET", "http://localhost:8000/users", None),
48 | ("POST", "http://localhost:8000/users", {"id": 3, "name": "Charlie", "email": "charlie@example.com", "age": 28}),
49 | ("POST", "http://localhost:8000/users", {"id": 4, "name": "David", "email": "invalid-email", "age": 22}), # Invalid email
50 | ("POST", "http://localhost:8000/users", {"name": "Eve", "email": "eve@example.com"}) # Missing id
51 | ]
52 |
53 | for method, url, data in requests_list:
54 | try:
55 | if method == "GET":
56 | response = requests.get(url)
57 | else:
58 | response = requests.post(url, json=data)
59 | response.raise_for_status()
60 | success_counts["Successful"] += 1
61 | print(f"{method} {url}: {response.status_code}")
62 | except requests.RequestException as e:
63 | success_counts["Failed"] += 1
64 | print(f"Error for {method} {url}: {e}")
65 |
66 | # Visualization
67 | plt.figure(figsize=(6, 4))
68 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
69 | plt.title("Data Validation Request Success")
70 | plt.xlabel("Status")
71 | plt.ylabel("Count")
72 | plt.savefig("data_validation_pydantic_output.png")
73 | print("Visualization: Validation success saved as data_validation_pydantic_output.png")
74 |
75 | # Run FastAPI server in a thread
76 | def run_server():
77 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
78 |
79 | if __name__ == "__main__":
80 | # Start server in a separate thread
81 | server_thread = threading.Thread(target=run_server)
82 | server_thread.daemon = True
83 | server_thread.start()
84 |
85 | # Wait for server to start
86 | time.sleep(2)
87 |
88 | # Test validation
89 | test_validation()
90 |
91 | # Keep the main thread alive briefly to view results
92 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/02 API Development/03 Response Metrics Visualization/response_metrics_visualization.py:
--------------------------------------------------------------------------------
1 | # %% response_metrics_visualization.py
2 | # Setup: pip install fastapi uvicorn pydantic requests matplotlib pandas
3 | from fastapi import FastAPI
4 | from pydantic import BaseModel
5 | import uvicorn
6 | import requests
7 | import matplotlib.pyplot as plt
8 | import time
9 | import threading
10 |
11 | app = FastAPI()
12 |
13 | # Pydantic Model
14 | class Item(BaseModel):
15 | id: int
16 | name: str
17 | price: float
18 |
19 | # Synthetic Data
20 | items = [
21 | {"id": 1, "name": "Laptop", "price": 999.99},
22 | {"id": 2, "name": "Phone", "price": 499.99}
23 | ]
24 |
25 | # Endpoints
26 | @app.get("/items")
27 | def get_items():
28 | return items
29 |
30 | @app.get("/items/{item_id}")
31 | def get_item(item_id: int):
32 | for item in items:
33 | if item["id"] == item_id:
34 | return item
35 | return {"error": "Item not found"}, 404
36 |
37 | @app.post("/items")
38 | def create_item(item: Item):
39 | items.append(item.dict())
40 | return item, 201
41 |
42 | # Function to measure and visualize response metrics
43 | def visualize_metrics():
44 | print("Synthetic Data: Items created")
45 | print(f"Items: {items}")
46 |
47 | # Track response times
48 | response_times = []
49 |
50 | # Test endpoints
51 | requests_list = [
52 | ("GET", "http://localhost:8000/items"),
53 | ("GET", "http://localhost:8000/items/1"),
54 | ("GET", "http://localhost:8000/items/999"),
55 | ("POST", "http://localhost:8000/items", {"id": 3, "name": "Tablet", "price": 299.99})
56 | ]
57 |
58 | for method, url, *data in requests_list:
59 | start_time = time.time()
60 | try:
61 | if method == "GET":
62 | response = requests.get(url)
63 | else:
64 | response = requests.post(url, json=data[0])
65 | response.raise_for_status()
66 | elapsed_time = time.time() - start_time
67 | response_times.append(elapsed_time)
68 | print(f"{method} {url}: {response.status_code} ({elapsed_time:.3f}s)")
69 | except requests.RequestException as e:
70 | response_times.append(0) # Record 0 for failed requests
71 | print(f"Error for {method} {url}: {e}")
72 |
73 | # Visualization
74 | plt.figure(figsize=(8, 4))
75 | plt.plot(range(1, len(response_times) + 1), response_times, marker='o', color='blue')
76 | plt.title("API Response Times")
77 | plt.xlabel("Request")
78 | plt.ylabel("Response Time (seconds)")
79 | plt.grid(True)
80 | plt.savefig("response_metrics_visualization_output.png")
81 | print("Visualization: Response times saved as response_metrics_visualization_output.png")
82 |
83 | # Run FastAPI server in a thread
84 | def run_server():
85 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
86 |
87 | if __name__ == "__main__":
88 | # Start server in a separate thread
89 | server_thread = threading.Thread(target=run_server)
90 | server_thread.daemon = True
91 | server_thread.start()
92 |
93 | # Wait for server to start
94 | time.sleep(2)
95 |
96 | # Visualize metrics
97 | visualize_metrics()
98 |
99 | # Keep the main thread alive briefly to view results
100 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/02 API Development/README.md:
--------------------------------------------------------------------------------
1 | # 📝 FastAPI API Development with Python Roadmap
2 |
3 |
9 | Your step-by-step guide to mastering API development with FastAPI and Python, from dynamic parameters to response metrics visualization, for building robust APIs and preparing for backend development interviews
10 |
11 | ---
12 |
13 | ## 📖 Introduction
14 |
15 | Welcome to the **FastAPI API Development with Python Roadmap**! 🚀 This roadmap is designed to advance your FastAPI skills by focusing on creating dynamic, validated, and performant APIs. It covers handling path and query parameters, validating data with Pydantic, and visualizing response metrics. Aligned with the tech-driven era (May 3, 2025), this roadmap equips you with practical skills for backend development, AI/ML integration, and interview preparation for 6 LPA+ roles.
16 |
17 | ## 🌟 What’s Inside?
18 |
19 | - **Path and Query Parameters**: Creating dynamic endpoints with URL parameters.
20 | - **Data Validation with Pydantic**: Ensuring robust data input with Pydantic models.
21 | - **Response Metrics Visualization**: Monitoring and visualizing API performance metrics.
22 | - **Hands-on Code**: Three Python scripts with examples and visualizations.
23 | - **Interview Scenarios**: Key questions and answers for API development.
24 |
25 | ## 🔍 Who Is This For?
26 |
27 | - Backend Developers building dynamic RESTful APIs.
28 | - AI/ML Engineers serving models via validated APIs.
29 | - Software Engineers deepening FastAPI expertise.
30 | - Anyone preparing for backend or AI/ML interviews.
31 |
32 | ## 🗺️ Learning Roadmap
33 |
34 | This roadmap covers three key areas of API development, each with a dedicated Python script:
35 |
36 | ### 📌 Path and Query Parameters (`path_query_parameters.py`)
37 | - Dynamic Path Parameters
38 | - Optional Query Parameters
39 | - Parameter Validation
40 |
41 | ### 📋 Data Validation with Pydantic (`data_validation_pydantic.py`)
42 | - Pydantic Model Creation
43 | - Automatic Data Validation
44 | - Error Handling for Invalid Inputs
45 |
46 | ### 📊 Response Metrics Visualization (`response_metrics_visualization.py`)
47 | - Measuring Response Times
48 | - Visualizing API Performance
49 | - Analyzing Request Success Rates
50 |
51 | ## 💡 Why Master FastAPI API Development?
52 |
53 | FastAPI excels in building robust APIs:
54 | 1. **Flexibility**: Dynamic parameters for versatile endpoints.
55 | 2. **Reliability**: Pydantic ensures data integrity.
56 | 3. **Performance Insights**: Metrics visualization aids optimization.
57 | 4. **Interview Relevance**: Tested in backend coding challenges.
58 |
59 | ## 📆 Study Plan
60 |
61 | - **Week 1**:
62 | - Day 1: Path and Query Parameters
63 | - Day 2: Data Validation with Pydantic
64 | - Day 3: Response Metrics Visualization
65 | - Day 4-5: Review scripts and practice interview scenarios
66 | - Day 6-7: Build an API combining all concepts
67 |
68 | ## 🛠️ Setup Instructions
69 |
70 | 1. **Python Environment**:
71 | - Install Python 3.8+ and pip.
72 | - Create a virtual environment: `python -m venv fastapi_env; source fastapi_env/bin/activate`.
73 | - Install dependencies: `pip install fastapi uvicorn pydantic requests matplotlib pandas`.
74 | 2. **Running FastAPI**:
75 | - Run a FastAPI app: `uvicorn main:app --reload`.
76 | - Access the app at `http://localhost:8000` and docs at `http://localhost:8000/docs`.
77 | 3. **Datasets**:
78 | - Uses synthetic data (e.g., items, users).
79 | - Note: Code uses simulated data to avoid file I/O constraints.
80 | 4. **Running Code**:
81 | - Copy code from `.py` files into a Python environment.
82 | - Use VS Code, PyCharm, or Google Colab.
83 | - View outputs in terminal, browser (Swagger UI), and Matplotlib visualizations (PNGs).
84 | - Check terminal for errors; ensure dependencies are installed.
85 |
86 | ## 🏆 Practical Tasks
87 |
88 | 1. **Path and Query Parameters**:
89 | - Create endpoints with path and query parameters.
90 | - Test filtering with query parameters.
91 | 2. **Data Validation with Pydantic**:
92 | - Define a Pydantic model for data validation.
93 | - Handle invalid input errors.
94 | 3. **Response Metrics Visualization**:
95 | - Measure API response times.
96 | - Visualize performance metrics.
97 |
98 | ## 💡 Interview Tips
99 |
100 | - **Common Questions**:
101 | - How do you use path and query parameters in FastAPI?
102 | - What is Pydantic, and how does it work with FastAPI?
103 | - How do you measure and optimize API performance?
104 | - **Tips**:
105 | - Explain parameter handling with code (e.g., `@app.get("/items/{id}")`).
106 | - Demonstrate Pydantic validation with examples.
107 | - Code tasks like validating input or measuring response times.
108 | - Discuss FastAPI’s automatic validation and documentation.
109 | - **Coding Tasks**:
110 | - Build an endpoint with query parameters and Pydantic validation.
111 | - Visualize API response metrics.
112 | - **Conceptual Clarity**:
113 | - Explain how Pydantic enhances API reliability.
114 | - Describe the importance of performance metrics.
115 |
116 | ## 📚 Resources
117 |
118 | - [FastAPI Documentation](https://fastapi.tiangolo.com/)
119 | - [Pydantic Documentation](https://pydantic-docs.helpmanual.io/)
120 | - [Uvicorn Documentation](https://www.uvicorn.org/)
121 | - [Matplotlib Documentation](https://matplotlib.org/stable/contents.html)
122 |
123 | ## 🤝 Contributions
124 |
125 | 1. Fork the repository.
126 | 2. Create a feature branch (`git checkout -b feature/api-development`).
127 | 3. Commit changes (`git commit -m 'Add API development content'`).
128 | 4. Push to the branch (`git push origin feature/api-development`).
129 | 5. Open a Pull Request.
130 |
131 | ---
132 |
133 |
134 |
Happy Learning and Good Luck with Your Interviews! ✨
135 |
--------------------------------------------------------------------------------
/Fast API Fundamentals/03 Advanced FastAPI Features/01 Authentication and Authorization/authentication_authorization.py:
--------------------------------------------------------------------------------
1 | # %% authentication_authorization.py
2 | # Setup: pip install fastapi uvicorn pydantic python-jose[cryptography] passlib[bcrypt] requests matplotlib pandas
3 | from fastapi import FastAPI, Depends, HTTPException, status
4 | from fastapi.security import OAuth2PasswordBearer
5 | from pydantic import BaseModel
6 | from jose import JWTError, jwt
7 | from passlib.context import CryptContext
8 | import uvicorn
9 | import requests
10 | import matplotlib.pyplot as plt
11 | from collections import Counter
12 | import threading
13 | import time
14 |
15 | app = FastAPI()
16 |
17 | # JWT Configuration
18 | SECRET_KEY = "your-secret-key"
19 | ALGORITHM = "HS256"
20 | pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
21 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
22 |
23 | # Pydantic Models
24 | class User(BaseModel):
25 | username: str
26 | role: str
27 |
28 | # Synthetic Data
29 | users_db = {
30 | "admin": {"username": "admin", "password": pwd_context.hash("adminpass"), "role": "admin"},
31 | "user": {"username": "user", "password": pwd_context.hash("userpass"), "role": "user"}
32 | }
33 |
34 | # JWT Functions
35 | def verify_password(plain_password, hashed_password):
36 | return pwd_context.verify(plain_password, hashed_password)
37 |
38 | def create_access_token(data: dict):
39 | return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)
40 |
41 | async def get_current_user(token: str = Depends(oauth2_scheme)):
42 | try:
43 | payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
44 | username: str = payload.get("sub")
45 | if username not in users_db:
46 | raise HTTPException(status_code=401, detail="Invalid credentials")
47 | return User(username=username, role=users_db[username]["role"])
48 | except JWTError:
49 | raise HTTPException(status_code=401, detail="Invalid token")
50 |
51 | # Endpoints
52 | @app.post("/token")
53 | async def login(username: str, password: str):
54 | user = users_db.get(username)
55 | if not user or not verify_password(password, user["password"]):
56 | raise HTTPException(status_code=401, detail="Incorrect username or password")
57 | access_token = create_access_token(data={"sub": username})
58 | return {"access_token": access_token, "token_type": "bearer"}
59 |
60 | @app.get("/protected")
61 | async def protected_route(current_user: User = Depends(get_current_user)):
62 | if current_user.role != "admin":
63 | raise HTTPException(status_code=403, detail="Not authorized")
64 | return {"message": "This is a protected admin route", "user": current_user.username}
65 |
66 | # Function to test authentication and authorization
67 | def test_auth():
68 | print("Synthetic Data: Users created")
69 | print(f"Users: {list(users_db.keys())}")
70 |
71 | # Track request success
72 | success_counts = {"Successful": 0, "Failed": 0}
73 |
74 | # Test login and protected route
75 | tests = [
76 | ("POST", "http://localhost:8000/token", {"username": "admin", "password": "adminpass"}),
77 | ("POST", "http://localhost:8000/token", {"username": "user", "password": "wrongpass"}),
78 | ("GET", "http://localhost:8000/protected", None, "admin"),
79 | ("GET", "http://localhost:8000/protected", None, "user")
80 | ]
81 |
82 | admin_token = None
83 | for method, url, data, *user in tests:
84 | try:
85 | if method == "POST":
86 | response = requests.post(url, json=data)
87 | if response.status_code == 200 and data["username"] == "admin":
88 | admin_token = response.json()["access_token"]
89 | else:
90 | headers = {"Authorization": f"Bearer {admin_token}" if user[0] == "admin" else "Bearer invalid"}
91 | response = requests.get(url, headers=headers)
92 | response.raise_for_status()
93 | success_counts["Successful"] += 1
94 | print(f"{method} {url}: {response.status_code}")
95 | except requests.RequestException as e:
96 | success_counts["Failed"] += 1
97 | print(f"Error for {method} {url}: {e}")
98 |
99 | # Visualization
100 | plt.figure(figsize=(6, 4))
101 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
102 | plt.title("Authentication Request Success")
103 | plt.xlabel("Status")
104 | plt.ylabel("Count")
105 | plt.savefig("authentication_authorization_output.png")
106 | print("Visualization: Auth success saved as authentication_authorization_output.png")
107 |
108 | # Run FastAPI server in a thread
109 | def run_server():
110 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
111 |
112 | if __name__ == "__main__":
113 | # Start server in a separate thread
114 | server_thread = threading.Thread(target=run_server)
115 | server_thread.daemon = True
116 | server_thread.start()
117 |
118 | # Wait for server to start
119 | time.sleep(2)
120 |
121 | # Test authentication
122 | test_auth()
123 |
124 | # Keep the main thread alive briefly to view results
125 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/03 Advanced FastAPI Features/02 Middleware and Async Programming/middleware_async.py:
--------------------------------------------------------------------------------
1 | # %% middleware_async.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI, Request
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 | import asyncio
11 |
12 | app = FastAPI()
13 |
14 | # Synthetic Data
15 | requests_log = []
16 |
17 | # Custom Middleware
18 | @app.middleware("http")
19 | async def log_requests(request: Request, call_next):
20 | start_time = time.time()
21 | response = await call_next(request)
22 | duration = time.time() - start_time
23 | requests_log.append({"path": str(request.url.path), "duration": duration})
24 | return response
25 |
26 | # Async Endpoints
27 | @app.get("/items")
28 | async def get_items():
29 | await asyncio.sleep(0.1) # Simulate async work
30 | return [{"id": 1, "name": "Laptop"}, {"id": 2, "name": "Phone"}]
31 |
32 | @app.get("/items/{item_id}")
33 | async def get_item(item_id: int):
34 | await asyncio.sleep(0.05) # Simulate async work
35 | items = {1: "Laptop", 2: "Phone"}
36 | return {"id": item_id, "name": items.get(item_id, "Not found")}
37 |
38 | # Function to test middleware and async endpoints
39 | def test_middleware_async():
40 | print("Synthetic Data: Requests log initialized")
41 |
42 | # Track request success
43 | success_counts = {"Successful": 0, "Failed": 0}
44 |
45 | # Test async endpoints
46 | endpoints = [
47 | ("GET", "http://localhost:8000/items"),
48 | ("GET", "http://localhost:8000/items/1"),
49 | ("GET", "http://localhost:8000/items/999")
50 | ]
51 |
52 | for method, url in endpoints:
53 | try:
54 | response = requests.get(url)
55 | response.raise_for_status()
56 | success_counts["Successful"] += 1
57 | print(f"{method} {url}: {response.status_code}")
58 | except requests.RequestException as e:
59 | success_counts["Failed"] += 1
60 | print(f"Error for {method} {url}: {e}")
61 |
62 | # Visualization of request durations
63 | durations = [log["duration"] for log in requests_log]
64 | plt.figure(figsize=(8, 4))
65 | plt.plot(range(1, len(durations) + 1), durations, marker='o', color='blue')
66 | plt.title("Request Durations (Middleware)")
67 | plt.xlabel("Request")
68 | plt.ylabel("Duration (seconds)")
69 | plt.grid(True)
70 | plt.savefig("middleware_async_output.png")
71 | print("Visualization: Request durations saved as middleware_async_output.png")
72 |
73 | # Run FastAPI server in a thread
74 | def run_server():
75 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
76 |
77 | if __name__ == "__main__":
78 | # Start server in a separate thread
79 | server_thread = threading.Thread(target=run_server)
80 | server_thread.daemon = True
81 | server_thread.start()
82 |
83 | # Wait for server to start
84 | time.sleep(2)
85 |
86 | # Test middleware and async
87 | test_middleware_async()
88 |
89 | # Keep the main thread alive briefly to view results
90 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/03 Advanced FastAPI Features/03 Performance Metrics Visualization/performance_metrics_visualization.py:
--------------------------------------------------------------------------------
1 | # %% performance_metrics_visualization.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | import time
8 | import threading
9 |
10 | app = FastAPI()
11 |
12 | # Synthetic Data
13 | items = [
14 | {"id": 1, "name": "Laptop", "price": 999.99},
15 | {"id": 2, "name": "Phone", "price": 499.99}
16 | ]
17 |
18 | # Endpoints
19 | @app.get("/items")
20 | async def get_items():
21 | return items
22 |
23 | @app.get("/items/{item_id}")
24 | async def get_item(item_id: int):
25 | for item in items:
26 | if item["id"] == item_id:
27 | return item
28 | return {"error": "Item not found"}, 404
29 |
30 | @app.post("/items")
31 | async def create_item(item: dict):
32 | items.append(item)
33 | return item, 201
34 |
35 | # Function to measure and visualize performance metrics
36 | def visualize_performance():
37 | print("Synthetic Data: Items created")
38 | print(f"Items: {items}")
39 |
40 | # Track performance metrics
41 | response_times = []
42 | success_counts = {"Successful": 0, "Failed": 0}
43 |
44 | # Test endpoints with multiple requests
45 | requests_list = [
46 | ("GET", "http://localhost:8000/items"),
47 | ("GET", "http://localhost:8000/items/1"),
48 | ("GET", "http://localhost:8000/items/999"),
49 | ("POST", "http://localhost:8000/items", {"id": 3, "name": "Tablet", "price": 299.99})
50 | ]
51 |
52 | for method, url, *data in requests_list:
53 | start_time = time.time()
54 | try:
55 | if method == "GET":
56 | response = requests.get(url)
57 | else:
58 | response = requests.post(url, json=data[0])
59 | response.raise_for_status()
60 | elapsed_time = time.time() - start_time
61 | response_times.append(elapsed_time)
62 | success_counts["Successful"] += 1
63 | print(f"{method} {url}: {response.status_code} ({elapsed_time:.3f}s)")
64 | except requests.RequestException as e:
65 | response_times.append(0)
66 | success_counts["Failed"] += 1
67 | print(f"Error for {method} {url}: {e}")
68 |
69 | # Visualization
70 | plt.figure(figsize=(8, 4))
71 | plt.subplot(1, 2, 1)
72 | plt.plot(range(1, len(response_times) + 1), response_times, marker='o', color='blue')
73 | plt.title("Response Times")
74 | plt.xlabel("Request")
75 | plt.ylabel("Time (seconds)")
76 | plt.grid(True)
77 |
78 | plt.subplot(1, 2, 2)
79 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
80 | plt.title("Request Success")
81 | plt.xlabel("Status")
82 | plt.ylabel("Count")
83 |
84 | plt.tight_layout()
85 | plt.savefig("performance_metrics_visualization_output.png")
86 | print("Visualization: Performance metrics saved as performance_metrics_visualization_output.png")
87 |
88 | # Run FastAPI server in a thread
89 | def run_server():
90 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
91 |
92 | if __name__ == "__main__":
93 | # Start server in a separate thread
94 | server_thread = threading.Thread(target=run_server)
95 | server_thread.daemon = True
96 | server_thread.start()
97 |
98 | # Wait for server to start
99 | time.sleep(2)
100 |
101 | # Visualize performance
102 | visualize_performance()
103 |
104 | # Keep the main thread alive briefly to view results
105 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/03 Advanced FastAPI Features/README.md:
--------------------------------------------------------------------------------
1 | # ⚙️ Advanced FastAPI Features with Python Roadmap
2 |
3 |
9 | Your step-by-step guide to mastering advanced FastAPI features with Python, from authentication to performance visualization, for building secure and optimized APIs and preparing for backend development interviews
10 |
11 | ---
12 |
13 | ## 📖 Introduction
14 |
15 | Welcome to the **Advanced FastAPI Features with Python Roadmap**! 🚀 This roadmap is designed to deepen your FastAPI expertise by exploring advanced features like authentication, middleware, async programming, and performance visualization. Aligned with the tech-driven era (May 3, 2025), this roadmap equips you with practical skills for building secure, scalable APIs and preparing for backend and AI/ML interviews for 6 LPA+ roles.
16 |
17 | ## 🌟 What’s Inside?
18 |
19 | - **Authentication and Authorization**: Implementing secure user access with JWT.
20 | - **Middleware and Async Programming**: Enhancing APIs with middleware and async/await.
21 | - **Performance Metrics Visualization**: Monitoring and visualizing API performance.
22 | - **Hands-on Code**: Three Python scripts with examples and visualizations.
23 | - **Interview Scenarios**: Key questions and answers for advanced FastAPI topics.
24 |
25 | ## 🔍 Who Is This For?
26 |
27 | - Backend Developers building secure and scalable APIs.
28 | - AI/ML Engineers integrating models with protected endpoints.
29 | - Software Engineers mastering advanced web frameworks.
30 | - Anyone preparing for backend or AI/ML interviews.
31 |
32 | ## 🗺️ Learning Roadmap
33 |
34 | This roadmap covers three key areas of advanced FastAPI features, each with a dedicated Python script:
35 |
36 | ### 🔒 Authentication and Authorization (`authentication_authorization.py`)
37 | - JWT-based Authentication
38 | - Role-based Authorization
39 | - Secure Endpoint Protection
40 |
41 | ### 🛠️ Middleware and Async Programming (`middleware_async.py`)
42 | - Custom Middleware for Request Processing
43 | - Async/Await for Non-blocking Operations
44 | - Handling Concurrent Requests
45 |
46 | ### 📊 Performance Metrics Visualization (`performance_metrics_visualization.py`)
47 | - Measuring Latency and Throughput
48 | - Visualizing Performance Metrics
49 | - Optimizing API Performance
50 |
51 | ## 💡 Why Master Advanced FastAPI Features?
52 |
53 | FastAPI’s advanced features empower robust API development:
54 | 1. **Security**: JWT ensures protected endpoints.
55 | 2. **Scalability**: Async programming handles high concurrency.
56 | 3. **Optimization**: Performance metrics guide improvements.
57 | 4. **Interview Relevance**: Tested in advanced backend challenges.
58 |
59 | ## 📆 Study Plan
60 |
61 | - **Week 1**:
62 | - Day 1: Authentication and Authorization
63 | - Day 2: Middleware and Async Programming
64 | - Day 3: Performance Metrics Visualization
65 | - Day 4-5: Review scripts and practice interview scenarios
66 | - Day 6-7: Build a secure, async API with performance monitoring
67 |
68 | ## 🛠️ Setup Instructions
69 |
70 | 1. **Python Environment**:
71 | - Install Python 3.8+ and pip.
72 | - Create a virtual environment: `python -m venv fastapi_env; source fastapi_env/bin/activate`.
73 | - Install dependencies: `pip install fastapi uvicorn pydantic python-jose[cryptography] passlib[bcrypt] requests matplotlib pandas`.
74 | 2. **Running FastAPI**:
75 | - Run a FastAPI app: `uvicorn main:app --reload`.
76 | - Access the app at `http://localhost:8000` and docs at `http://localhost:8000/docs`.
77 | 3. **Datasets**:
78 | - Uses synthetic data (e.g., users, requests).
79 | - Note: Code uses simulated data to avoid file I/O constraints.
80 | 4. **Running Code**:
81 | - Copy code from `.py` files into a Python environment.
82 | - Use VS Code, PyCharm, or Google Colab.
83 | - View outputs in terminal, browser (Swagger UI), and Matplotlib visualizations (PNGs).
84 | - Check terminal for errors; ensure dependencies are installed.
85 |
86 | ## 🏆 Practical Tasks
87 |
88 | 1. **Authentication and Authorization**:
89 | - Implement JWT authentication for a protected endpoint.
90 | - Add role-based access control.
91 | 2. **Middleware and Async Programming**:
92 | - Create custom middleware for logging requests.
93 | - Use async/await for non-blocking endpoints.
94 | 3. **Performance Metrics Visualization**:
95 | - Measure API latency and throughput.
96 | - Visualize performance metrics.
97 |
98 | ## 💡 Interview Tips
99 |
100 | - **Common Questions**:
101 | - How do you implement authentication in FastAPI?
102 | - What is middleware, and how is it used in FastAPI?
103 | - How does async programming improve API performance?
104 | - How do you measure and optimize API performance?
105 | - **Tips**:
106 | - Explain JWT authentication with code (e.g., `OAuth2PasswordBearer`).
107 | - Demonstrate middleware and async/await usage.
108 | - Code tasks like securing an endpoint or measuring latency.
109 | - Discuss trade-offs of async vs. sync programming.
110 | - **Coding Tasks**:
111 | - Implement a JWT-protected endpoint.
112 | - Create an async endpoint with middleware.
113 | - Visualize API performance metrics.
114 | - **Conceptual Clarity**:
115 | - Explain how JWT ensures security.
116 | - Describe the benefits of async programming in FastAPI.
117 |
118 | ## 📚 Resources
119 |
120 | - [FastAPI Documentation](https://fastapi.tiangolo.com/)
121 | - [Pydantic Documentation](https://pydantic-docs.helpmanual.io/)
122 | - [Python-Jose Documentation](https://python-jose.readthedocs.io/)
123 | - [Matplotlib Documentation](https://matplotlib.org/stable/contents.html)
124 |
125 | ## 🤝 Contributions
126 |
127 | 1. Fork the repository.
128 | 2. Create a feature branch (`git checkout -b feature/advanced-features`).
129 | 3. Commit changes (`git commit -m 'Add advanced FastAPI features content'`).
130 | 4. Push to the branch (`git push origin feature/advanced-features`).
131 | 5. Open a Pull Request.
132 |
133 | ---
134 |
135 |
136 |
Happy Learning and Good Luck with Your Interviews! ✨
137 |
--------------------------------------------------------------------------------
/Fast API Fundamentals/04 Testing and Documentation/01 Unit and Integration Testing/unit_integration_testing.py:
--------------------------------------------------------------------------------
1 | # %% unit_integration_testing.py
2 | # Setup: pip install fastapi uvicorn pytest requests matplotlib pandas
3 | from fastapi import FastAPI
4 | from fastapi.testclient import TestClient
5 | import pytest
6 | import uvicorn
7 | import requests
8 | import matplotlib.pyplot as plt
9 | from collections import Counter
10 | import threading
11 | import time
12 |
13 | app = FastAPI()
14 |
15 | # Synthetic Data
16 | items = [
17 | {"id": 1, "name": "Laptop", "price": 999.99},
18 | {"id": 2, "name": "Phone", "price": 499.99}
19 | ]
20 |
21 | # Endpoints
22 | @app.get("/items")
23 | def get_items():
24 | return items
25 |
26 | @app.get("/items/{item_id}")
27 | def get_item(item_id: int):
28 | for item in items:
29 | if item["id"] == item_id:
30 | return item
31 | return {"error": "Item not found"}, 404
32 |
33 | @app.post("/items")
34 | def create_item(item: dict):
35 | items.append(item)
36 | return item, 201
37 |
38 | # Unit and Integration Tests
39 | @pytest.fixture
40 | def client():
41 | return TestClient(app)
42 |
43 | def test_get_items(client):
44 | response = client.get("/items")
45 | assert response.status_code == 200
46 | assert response.json() == items
47 |
48 | def test_get_item(client):
49 | response = client.get("/items/1")
50 | assert response.status_code == 200
51 | assert response.json() == {"id": 1, "name": "Laptop", "price": 999.99}
52 |
53 | def test_get_item_not_found(client):
54 | response = client.get("/items/999")
55 | assert response.status_code == 200
56 | assert response.json() == {"error": "Item not found"}
57 |
58 | def test_create_item(client):
59 | new_item = {"id": 3, "name": "Tablet", "price": 299.99}
60 | response = client.post("/items", json=new_item)
61 | assert response.status_code == 201
62 | assert response.json() == new_item
63 |
64 | # Function to run tests and visualize results
65 | def run_tests():
66 | print("Synthetic Data: Items created")
67 | print(f"Items: {items}")
68 |
69 | # Track test results
70 | success_counts = {"Passed": 0, "Failed": 0}
71 |
72 | # Run tests manually to capture results
73 | client = TestClient(app)
74 | tests = [
75 | test_get_items,
76 | test_get_item,
77 | test_get_item_not_found,
78 | test_create_item
79 | ]
80 |
81 | for test_func in tests:
82 | try:
83 | test_func(client)
84 | success_counts["Passed"] += 1
85 | print(f"Test {test_func.__name__}: Passed")
86 | except AssertionError as e:
87 | success_counts["Failed"] += 1
88 | print(f"Test {test_func.__name__}: Failed - {e}")
89 |
90 | # Visualization
91 | plt.figure(figsize=(6, 4))
92 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
93 | plt.title("Test Results")
94 | plt.xlabel("Status")
95 | plt.ylabel("Count")
96 | plt.savefig("unit_integration_testing_output.png")
97 | print("Visualization: Test results saved as unit_integration_testing_output.png")
98 |
99 | # Run FastAPI server in a thread
100 | def run_server():
101 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
102 |
103 | if __name__ == "__main__":
104 | # Start server in a separate thread
105 | server_thread = threading.Thread(target=run_server)
106 | server_thread.daemon = True
107 | server_thread.start()
108 |
109 | # Wait for server to start
110 | time.sleep(2)
111 |
112 | # Run tests
113 | run_tests()
114 |
115 | # Keep the main thread alive briefly to view results
116 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/04 Testing and Documentation/02 Automatic API Documentation/automatic_api_documentation.py:
--------------------------------------------------------------------------------
1 | # %% automatic_api_documentation.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI(
12 | title="Sample FastAPI App",
13 | description="A sample API for demonstrating automatic documentation",
14 | version="1.0.0",
15 | docs_url="/docs",
16 | redoc_url="/redoc"
17 | )
18 |
19 | # Synthetic Data
20 | users = [
21 | {"id": 1, "name": "Alice", "email": "alice@example.com"},
22 | {"id": 2, "name": "Bob", "email": "bob@example.com"}
23 | ]
24 |
25 | # Endpoints with documentation
26 | @app.get("/users", summary="Get all users", description="Returns a list of all users")
27 | def get_users():
28 | return users
29 |
30 | @app.get("/users/{user_id}", summary="Get a user by ID", description="Returns a single user by ID")
31 | def get_user(user_id: int):
32 | for user in users:
33 | if user["id"] == user_id:
34 | return user
35 | return {"error": "User not found"}, 404
36 |
37 | @app.post("/users", summary="Create a user", description="Creates a new user")
38 | def create_user(user: dict):
39 | users.append(user)
40 | return user, 201
41 |
42 | # Function to test documentation accessibility
43 | def test_documentation():
44 | print("Synthetic Data: Users created")
45 | print(f"Users: {users}")
46 |
47 | # Track request success
48 | success_counts = {"Successful": 0, "Failed": 0}
49 |
50 | # Test documentation endpoints
51 | endpoints = [
52 | ("GET", "http://localhost:8000/docs"), # Swagger UI
53 | ("GET", "http://localhost:8000/redoc"), # ReDoc
54 | ("GET", "http://localhost:8000/users") # API endpoint for reference
55 | ]
56 |
57 | for method, url in endpoints:
58 | try:
59 | response = requests.get(url)
60 | response.raise_for_status()
61 | success_counts["Successful"] += 1
62 | print(f"{method} {url}: {response.status_code}")
63 | except requests.RequestException as e:
64 | success_counts["Failed"] += 1
65 | print(f"Error for {method} {url}: {e}")
66 |
67 | # Visualization
68 | plt.figure(figsize=(6, 4))
69 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
70 | plt.title("Documentation Accessibility")
71 | plt.xlabel("Status")
72 | plt.ylabel("Count")
73 | plt.savefig("automatic_api_documentation_output.png")
74 | print("Visualization: Documentation access saved as automatic_api_documentation_output.png")
75 |
76 | # Run FastAPI server in a thread
77 | def run_server():
78 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
79 |
80 | if __name__ == "__main__":
81 | # Start server in a separate thread
82 | server_thread = threading.Thread(target=run_server)
83 | server_thread.daemon = True
84 | server_thread.start()
85 |
86 | # Wait for server to start
87 | time.sleep(2)
88 |
89 | # Test documentation
90 | test_documentation()
91 |
92 | # Keep the main thread alive briefly to view results
93 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/04 Testing and Documentation/03 Test Coverage Visualization/test_coverage_visualization.py:
--------------------------------------------------------------------------------
1 | # %% test_coverage_visualization.py
2 | # Setup: pip install fastapi uvicorn pytest pytest-cov requests matplotlib pandas
3 | from fastapi import FastAPI
4 | from fastapi.testclient import TestClient
5 | import pytest
6 | import uvicorn
7 | import requests
8 | import matplotlib.pyplot as plt
9 | import subprocess
10 | import re
11 | import threading
12 | import time
13 |
14 | app = FastAPI()
15 |
16 | # Synthetic Data
17 | items = [
18 | {"id": 1, "name": "Laptop", "price": 999.99},
19 | {"id": 2, "name": "Phone", "price": 499.99}
20 | ]
21 |
22 | # Endpoints
23 | @app.get("/items")
24 | def get_items():
25 | return items
26 |
27 | @app.get("/items/{item_id}")
28 | def get_item(item_id: int):
29 | for item in items:
30 | if item["id"] == item_id:
31 | return item
32 | return {"error": "Item not found"}, 404
33 |
34 | @app.post("/items")
35 | def create_item(item: dict):
36 | items.append(item)
37 | return item, 201
38 |
39 | # Unit Tests
40 | @pytest.fixture
41 | def client():
42 | return TestClient(app)
43 |
44 | def test_get_items(client):
45 | response = client.get("/items")
46 | assert response.status_code == 200
47 | assert response.json() == items
48 |
49 | def test_get_item(client):
50 | response = client.get("/items/1")
51 | assert response.status_code == 200
52 | assert response.json() == {"id": 1, "name": "Laptop", "price": 999.99}
53 |
54 | # Function to run tests and visualize coverage
55 | def visualize_coverage():
56 | print("Synthetic Data: Items created")
57 | print(f"Items: {items}")
58 |
59 | # Run pytest with coverage
60 | try:
61 | result = subprocess.run(
62 | ["pytest", "--cov=.", "--cov-report=term", __file__],
63 | capture_output=True, text=True
64 | )
65 | output = result.stdout
66 | print("Pytest Output:", output)
67 |
68 | # Extract coverage percentage
69 | match = re.search(r"TOTAL\s+\d+\s+\d+\s+(\d+)%", output)
70 | coverage = int(match.group(1)) if match else 0
71 | except Exception as e:
72 | print(f"Error running pytest: {e}")
73 | coverage = 0
74 |
75 | # Visualization
76 | plt.figure(figsize=(6, 4))
77 | plt.bar(["Covered", "Uncovered"], [coverage, 100 - coverage], color=['green', 'red'])
78 | plt.title("Test Coverage")
79 | plt.xlabel("Status")
80 | plt.ylabel("Percentage")
81 | plt.savefig("test_coverage_visualization_output.png")
82 | print("Visualization: Coverage saved as test_coverage_visualization_output.png")
83 |
84 | # Run FastAPI server in a thread
85 | def run_server():
86 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
87 |
88 | if __name__ == "__main__":
89 | # Start server in a separate thread
90 | server_thread = threading.Thread(target=run_server)
91 | server_thread.daemon = True
92 | server_thread.start()
93 |
94 | # Wait for server to start
95 | time.sleep(2)
96 |
97 | # Visualize coverage
98 | visualize_coverage()
99 |
100 | # Keep the main thread alive briefly to view results
101 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/04 Testing and Documentation/README.md:
--------------------------------------------------------------------------------
1 | # 🧪 FastAPI Testing and Documentation with Python Roadmap
2 |
3 |
9 | Your step-by-step guide to mastering testing and documentation with FastAPI and Python, from unit tests to visualizing test coverage, for building reliable APIs and preparing for backend development interviews
10 |
11 | ---
12 |
13 | ## 📖 Introduction
14 |
15 | Welcome to the **FastAPI Testing and Documentation with Python Roadmap**! 🚀 This roadmap is designed to teach you how to test FastAPI applications, generate automatic API documentation, and visualize test coverage. Aligned with the tech-driven era (May 3, 2025), this roadmap equips you with practical skills for ensuring API reliability, improving documentation, and preparing for backend and AI/ML interviews for 6 LPA+ roles.
16 |
17 | ## 🌟 What’s Inside?
18 |
19 | - **Unit and Integration Testing**: Writing tests for FastAPI endpoints using Pytest.
20 | - **Automatic API Documentation**: Leveraging FastAPI’s Swagger UI and ReDoc.
21 | - **Test Coverage Visualization**: Measuring and visualizing test coverage.
22 | - **Hands-on Code**: Three Python scripts with examples and visualizations.
23 | - **Interview Scenarios**: Key questions and answers for testing and documentation.
24 |
25 | ## 🔍 Who Is This For?
26 |
27 | - Backend Developers ensuring API reliability through testing.
28 | - AI/ML Engineers validating model-serving APIs.
29 | - Software Engineers mastering testing frameworks and documentation.
30 | - Anyone preparing for backend or AI/ML interviews.
31 |
32 | ## 🗺️ Learning Roadmap
33 |
34 | This roadmap covers three key areas of testing and documentation, each with a dedicated Python script:
35 |
36 | ### 🧪 Unit and Integration Testing (`unit_integration_testing.py`)
37 | - Writing Unit Tests for Endpoints
38 | - Creating Integration Tests for API Workflows
39 | - Using Pytest with FastAPI
40 |
41 | ### 📜 Automatic API Documentation (`automatic_api_documentation.py`)
42 | - Generating Swagger UI Documentation
43 | - Customizing API Metadata
44 | - Testing Documentation Accessibility
45 |
46 | ### 📊 Test Coverage Visualization (`test_coverage_visualization.py`)
47 | - Measuring Test Coverage with Pytest-Cov
48 | - Visualizing Coverage Metrics
49 | - Identifying Untested Code
50 |
51 | ## 💡 Why Master Testing and Documentation?
52 |
53 | Testing and documentation are critical for production-ready APIs:
54 | 1. **Reliability**: Tests ensure endpoints work as expected.
55 | 2. **Usability**: Automatic documentation simplifies API usage.
56 | 3. **Maintainability**: Coverage metrics guide code quality.
57 | 4. **Interview Relevance**: Tested in backend quality assurance challenges.
58 |
59 | ## 📆 Study Plan
60 |
61 | - **Week 1**:
62 | - Day 1: Unit and Integration Testing
63 | - Day 2: Automatic API Documentation
64 | - Day 3: Test Coverage Visualization
65 | - Day 4-5: Review scripts and practice interview scenarios
66 | - Day 6-7: Build a tested, documented API
67 |
68 | ## 🛠️ Setup Instructions
69 |
70 | 1. **Python Environment**:
71 | - Install Python 3.8+ and pip.
72 | - Create a virtual environment: `python -m venv fastapi_env; source fastapi_env/bin/activate`.
73 | - Install dependencies: `pip install fastapi uvicorn pytest pytest-cov requests matplotlib pandas`.
74 | 2. **Running FastAPI**:
75 | - Run a FastAPI app: `uvicorn main:app --reload`.
76 | - Access the app at `http://localhost:8000` and docs at `http://localhost:8000/docs`.
77 | 3. **Running Tests**:
78 | - Run tests with Pytest: `pytest .py`.
79 | - Generate coverage: `pytest --cov=. .py`.
80 | 4. **Datasets**:
81 | - Uses synthetic data (e.g., items, users).
82 | - Note: Code uses simulated data to avoid file I/O constraints.
83 | 5. **Running Code**:
84 | - Copy code from `.py` files into a Python environment.
85 | - Use VS Code, PyCharm, or Google Colab.
86 | - View outputs in terminal, browser (Swagger UI/ReDoc), and Matplotlib visualizations (PNGs).
87 | - Check terminal for errors; ensure dependencies are installed.
88 |
89 | ## 🏆 Practical Tasks
90 |
91 | 1. **Unit and Integration Testing**:
92 | - Write unit tests for a FastAPI endpoint.
93 | - Create integration tests for an API workflow.
94 | 2. **Automatic API Documentation**:
95 | - Generate Swagger UI for an API.
96 | - Customize API metadata (e.g., title, description).
97 | 3. **Test Coverage Visualization**:
98 | - Measure test coverage with Pytest-Cov.
99 | - Visualize coverage metrics.
100 |
101 | ## 💡 Interview Tips
102 |
103 | - **Common Questions**:
104 | - How do you test FastAPI endpoints?
105 | - What is the difference between unit and integration tests?
106 | - How does FastAPI generate automatic documentation?
107 | - How do you measure test coverage?
108 | - **Tips**:
109 | - Explain Pytest usage with FastAPI’s `TestClient`.
110 | - Demonstrate Swagger UI generation with code.
111 | - Code tasks like writing a test or checking coverage.
112 | - Discuss the importance of high test coverage.
113 | - **Coding Tasks**:
114 | - Write a Pytest test for a FastAPI endpoint.
115 | - Generate and customize API documentation.
116 | - Visualize test coverage for an API.
117 | - **Conceptual Clarity**:
118 | - Explain the role of testing in API reliability.
119 | - Describe how Swagger UI improves developer experience.
120 |
121 | ## 📚 Resources
122 |
123 | - [FastAPI Documentation](https://fastapi.tiangolo.com/)
124 | - [Pytest Documentation](https://docs.pytest.org/)
125 | - [Pytest-Cov Documentation](https://pytest-cov.readthedocs.io/)
126 | - [Matplotlib Documentation](https://matplotlib.org/stable/contents.html)
127 |
128 | ## 🤝 Contributions
129 |
130 | 1. Fork the repository.
131 | 2. Create a feature branch (`git checkout -b feature/testing-documentation`).
132 | 3. Commit changes (`git commit -m 'Add testing and documentation content'`).
133 | 4. Push to the branch (`git push origin feature/testing-documentation`).
134 | 5. Open a Pull Request.
135 |
136 | ---
137 |
138 |
139 |
Happy Learning and Good Luck with Your Interviews! ✨
140 |
--------------------------------------------------------------------------------
/Fast API Fundamentals/05 Deployment and Scaling/01 Dockerizing FastAPI Apps/dockerizing_fastapi.py:
--------------------------------------------------------------------------------
1 | # %% dockerizing_fastapi.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI()
12 |
13 | # Synthetic Data
14 | items = [
15 | {"id": 1, "name": "Laptop", "price": 999.99},
16 | {"id": 2, "name": "Phone", "price": 499.99}
17 | ]
18 |
19 | # Endpoints
20 | @app.get("/items")
21 | def get_items():
22 | return items
23 |
24 | @app.get("/items/{item_id}")
25 | def get_item(item_id: int):
26 | for item in items:
27 | if item["id"] == item_id:
28 | return item
29 | return {"error": "Item not found"}, 404
30 |
31 | # Simulate Dockerfile creation
32 | def create_dockerfile():
33 | dockerfile_content = """
34 | FROM python:3.8-slim
35 | WORKDIR /app
36 | COPY requirements.txt .
37 | RUN pip install --no-cache-dir -r requirements.txt
38 | COPY . .
39 | CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
40 | """
41 | print("Simulated Dockerfile created:")
42 | print(dockerfile_content)
43 | return dockerfile_content
44 |
45 | # Function to simulate Docker deployment and test
46 | def test_docker_deployment():
47 | print("Synthetic Data: Items created")
48 | print(f"Items: {items}")
49 |
50 | # Simulate Docker build and run
51 | print("Simulating Docker build and run...")
52 | create_dockerfile()
53 |
54 | # Track request success
55 | success_counts = {"Successful": 0, "Failed": 0}
56 |
57 | # Test API endpoints (simulating containerized app)
58 | endpoints = [
59 | ("GET", "http://localhost:8000/items"),
60 | ("GET", "http://localhost:8000/items/1"),
61 | ("GET", "http://localhost:8000/items/999")
62 | ]
63 |
64 | for method, url in endpoints:
65 | try:
66 | response = requests.get(url)
67 | response.raise_for_status()
68 | success_counts["Successful"] += 1
69 | print(f"{method} {url}: {response.status_code}")
70 | except requests.RequestException as e:
71 | success_counts["Failed"] += 1
72 | print(f"Error for {method} {url}: {e}")
73 |
74 | # Visualization
75 | plt.figure(figsize=(6, 4))
76 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
77 | plt.title("Dockerized API Request Success")
78 | plt.xlabel("Status")
79 | plt.ylabel("Count")
80 | plt.savefig("dockerizing_fastapi_output.png")
81 | print("Visualization: Docker deployment success saved as dockerizing_fastapi_output.png")
82 |
83 | # Run FastAPI server in a thread (simulating Docker container)
84 | def run_server():
85 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
86 |
87 | if __name__ == "__main__":
88 | # Start server in a separate thread
89 | server_thread = threading.Thread(target=run_server)
90 | server_thread.daemon = True
91 | server_thread.start()
92 |
93 | # Wait for server to start
94 | time.sleep(2)
95 |
96 | # Test Docker deployment
97 | test_docker_deployment()
98 |
99 | # Keep the main thread alive briefly to view results
100 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/05 Deployment and Scaling/02 Cloud Deployment (e.g., AWS, Heroku)/cloud_deployment.py:
--------------------------------------------------------------------------------
1 | # %% cloud_deployment.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | from collections import Counter
8 | import threading
9 | import time
10 |
11 | app = FastAPI()
12 |
13 | # Synthetic Data
14 | users = [
15 | {"id": 1, "name": "Alice", "email": "alice@example.com"},
16 | {"id": 2, "name": "Bob", "email": "bob@example.com"}
17 | ]
18 |
19 | # Endpoints
20 | @app.get("/users")
21 | def get_users():
22 | return users
23 |
24 | @app.get("/users/{user_id}")
25 | def get_user(user_id: int):
26 | for user in users:
27 | if user["id"] == user_id:
28 | return user
29 | return {"error": "User not found"}, 404
30 |
31 | # Simulate cloud deployment configuration
32 | def create_cloud_config():
33 | procfile_content = "web: uvicorn main:app --host=0.0.0.0 --port=$PORT"
34 | requirements_content = """
35 | fastapi==0.68.0
36 | uvicorn==0.15.0
37 | """
38 | print("Simulated cloud configuration created:")
39 | print("Procfile:")
40 | print(procfile_content)
41 | print("requirements.txt:")
42 | print(requirements_content)
43 | return procfile_content, requirements_content
44 |
45 | # Function to simulate cloud deployment and test
46 | def test_cloud_deployment():
47 | print("Synthetic Data: Users created")
48 | print(f"Users: {users}")
49 |
50 | # Simulate cloud deployment
51 | print("Simulating cloud deployment (e.g., AWS, Heroku)...")
52 | create_cloud_config()
53 |
54 | # Track request success
55 | success_counts = {"Successful": 0, "Failed": 0}
56 |
57 | # Test API endpoints (simulating cloud-deployed app)
58 | endpoints = [
59 | ("GET", "http://localhost:8000/users"),
60 | ("GET", "http://localhost:8000/users/1"),
61 | ("GET", "http://localhost:8000/users/999")
62 | ]
63 |
64 | for method, url in endpoints:
65 | try:
66 | response = requests.get(url)
67 | response.raise_for_status()
68 | success_counts["Successful"] += 1
69 | print(f"{method} {url}: {response.status_code}")
70 | except requests.RequestException as e:
71 | success_counts["Failed"] += 1
72 | print(f"Error for {method} {url}: {e}")
73 |
74 | # Visualization
75 | plt.figure(figsize=(6, 4))
76 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
77 | plt.title("Cloud Deployed API Request Success")
78 | plt.xlabel("Status")
79 | plt.ylabel("Count")
80 | plt.savefig("cloud_deployment_output.png")
81 | print("Visualization: Cloud deployment success saved as cloud_deployment_output.png")
82 |
83 | # Run FastAPI server in a thread (simulating cloud environment)
84 | def run_server():
85 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
86 |
87 | if __name__ == "__main__":
88 | # Start server in a separate thread
89 | server_thread = threading.Thread(target=run_server)
90 | server_thread.daemon = True
91 | server_thread.start()
92 |
93 | # Wait for server to start
94 | time.sleep(2)
95 |
96 | # Test cloud deployment
97 | test_cloud_deployment()
98 |
99 | # Keep the main thread alive briefly to view results
100 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/05 Deployment and Scaling/03 Scalability Metrics Visualization/scalability_metrics_visualization.py:
--------------------------------------------------------------------------------
1 | # %% scalability_metrics_visualization.py
2 | # Setup: pip install fastapi uvicorn requests matplotlib pandas
3 | from fastapi import FastAPI
4 | import uvicorn
5 | import requests
6 | import matplotlib.pyplot as plt
7 | import time
8 | import threading
9 | import concurrent.futures
10 |
11 | app = FastAPI()
12 |
13 | # Synthetic Data
14 | items = [
15 | {"id": 1, "name": "Laptop", "price": 999.99},
16 | {"id": 2, "name": "Phone", "price": 499.99}
17 | ]
18 |
19 | # Endpoints
20 | @app.get("/items")
21 | async def get_items():
22 | return items
23 |
24 | @app.get("/items/{item_id}")
25 | async def get_item(item_id: int):
26 | for item in items:
27 | if item["id"] == item_id:
28 | return item
29 | return {"error": "Item not found"}, 404
30 |
31 | # Function to simulate load testing and visualize scalability
32 | def visualize_scalability():
33 | print("Synthetic Data: Items created")
34 | print(f"Items: {items}")
35 |
36 | # Track response times
37 | response_times = []
38 | success_counts = {"Successful": 0, "Failed": 0}
39 |
40 | # Simulate load with concurrent requests
41 | endpoints = [
42 | ("GET", "http://localhost:8000/items"),
43 | ("GET", "http://localhost:8000/items/1"),
44 | ("GET", "http://localhost:8000/items/999")
45 | ]
46 | load_requests = endpoints * 5 # Simulate 15 requests
47 |
48 | def make_request(method, url):
49 | start_time = time.time()
50 | try:
51 | response = requests.get(url)
52 | response.raise_for_status()
53 | elapsed_time = time.time() - start_time
54 | return elapsed_time, True
55 | except requests.RequestException:
56 | return 0, False
57 |
58 | with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
59 | results = list(executor.map(lambda x: make_request(*x), [(m, u) for m, u in load_requests]))
60 |
61 | for elapsed_time, success in results:
62 | response_times.append(elapsed_time)
63 | success_counts["Successful" if success else "Failed"] += 1
64 | print(f"Request: {'Success' if success else 'Failed'} ({elapsed_time:.3f}s)")
65 |
66 | # Visualization
67 | plt.figure(figsize=(8, 4))
68 | plt.subplot(1, 2, 1)
69 | plt.plot(range(1, len(response_times) + 1), response_times, marker='o', color='blue')
70 | plt.title("Response Times Under Load")
71 | plt.xlabel("Request")
72 | plt.ylabel("Time (seconds)")
73 | plt.grid(True)
74 |
75 | plt.subplot(1, 2, 2)
76 | plt.bar(success_counts.keys(), success_counts.values(), color=['green', 'red'])
77 | plt.title("Request Success Under Load")
78 | plt.xlabel("Status")
79 | plt.ylabel("Count")
80 |
81 | plt.tight_layout()
82 | plt.savefig("scalability_metrics_visualization_output.png")
83 | print("Visualization: Scalability metrics saved as scalability_metrics_visualization_output.png")
84 |
85 | # Run FastAPI server in a thread
86 | def run_server():
87 | uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
88 |
89 | if __name__ == "__main__":
90 | # Start server in a separate thread
91 | server_thread = threading.Thread(target=run_server)
92 | server_thread.daemon = True
93 | server_thread.start()
94 |
95 | # Wait for server to start
96 | time.sleep(2)
97 |
98 | # Visualize scalability
99 | visualize_scalability()
100 |
101 | # Keep the main thread alive briefly to view results
102 | time.sleep(2)
--------------------------------------------------------------------------------
/Fast API Fundamentals/05 Deployment and Scaling/README.md:
--------------------------------------------------------------------------------
1 | # 🚀 FastAPI Deployment and Scaling with Python Roadmap
2 |
3 |
9 | Your step-by-step guide to mastering deployment and scaling with FastAPI and Python, from Dockerizing apps to visualizing scalability metrics, for building production-ready APIs and preparing for backend development interviews
10 |
11 | ---
12 |
13 | ## 📖 Introduction
14 |
15 | Welcome to the **FastAPI Deployment and Scaling with Python Roadmap**! 🚀 This roadmap is designed to teach you how to deploy and scale FastAPI applications using Docker and cloud platforms, while monitoring performance under load. Aligned with the tech-driven era (May 3, 2025), this roadmap equips you with practical skills for production-ready API deployment, scalability, and preparation for backend and AI/ML interviews for 6 LPA+ roles.
16 |
17 | ## 🌟 What’s Inside?
18 |
19 | - **Dockerizing FastAPI Apps**: Containerizing APIs with Docker.
20 | - **Cloud Deployment (e.g., AWS, Heroku)**: Deploying APIs to cloud platforms.
21 | - **Scalability Metrics Visualization**: Measuring and visualizing performance under load.
22 | - **Hands-on Code**: Three Python scripts with simulated deployment and visualizations.
23 | - **Interview Scenarios**: Key questions and answers for deployment and scaling.
24 |
25 | ## 🔍 Who Is This For?
26 |
27 | - Backend Developers deploying APIs to production.
28 | - AI/ML Engineers scaling model-serving APIs.
29 | - DevOps Engineers learning containerization and cloud deployment.
30 | - Anyone preparing for backend or AI/ML interviews.
31 |
32 | ## 🗺️ Learning Roadmap
33 |
34 | This roadmap covers three key areas of deployment and scaling, each with a dedicated Python script:
35 |
36 | ### 🐳 Dockerizing FastAPI Apps (`dockerizing_fastapi.py`)
37 | - Creating a Dockerfile for FastAPI
38 | - Simulating Docker Deployment
39 | - Testing Containerized API
40 |
41 | ### ☁️ Cloud Deployment (e.g., AWS, Heroku) (`cloud_deployment.py`)
42 | - Preparing FastAPI for Cloud Deployment
43 | - Simulating Cloud Platform Deployment
44 | - Testing Deployed API Accessibility
45 |
46 | ### 📊 Scalability Metrics Visualization (`scalability_metrics_visualization.py`)
47 | - Simulating Load Testing
48 | - Measuring Latency and Throughput
49 | - Visualizing Scalability Metrics
50 |
51 | ## 💡 Why Master Deployment and Scaling?
52 |
53 | Deployment and scaling are essential for production APIs:
54 | 1. **Portability**: Docker ensures consistent environments.
55 | 2. **Accessibility**: Cloud platforms enable global access.
56 | 3. **Performance**: Scalability metrics ensure reliability under load.
57 | 4. **Interview Relevance**: Tested in DevOps and backend challenges.
58 |
59 | ## 📆 Study Plan
60 |
61 | - **Week 1**:
62 | - Day 1: Dockerizing FastAPI Apps
63 | - Day 2: Cloud Deployment
64 | - Day 3: Scalability Metrics Visualization
65 | - Day 4-5: Review scripts and practice interview scenarios
66 | - Day 6-7: Deploy a sample API and analyze its scalability
67 |
68 | ## 🛠️ Setup Instructions
69 |
70 | 1. **Python Environment**:
71 | - Install Python 3.8+ and pip.
72 | - Create a virtual environment: `python -m venv fastapi_env; source fastapi_env/bin/activate`.
73 | - Install dependencies: `pip install fastapi uvicorn requests matplotlib pandas`.
74 | 2. **Docker Setup**:
75 | - Install Docker Desktop or Docker CLI.
76 | - Note: Python scripts simulate Docker behavior without requiring actual containerization.
77 | 3. **Running FastAPI**:
78 | - Run a FastAPI app: `uvicorn main:app --reload`.
79 | - Access the app at `http://localhost:8000` and docs at `http://localhost:8000/docs`.
80 | 4. **Datasets**:
81 | - Uses synthetic data (e.g., items, requests).
82 | - Note: Code uses simulated data to avoid file I/O constraints.
83 | 5. **Running Code**:
84 | - Copy code from `.py` files into a Python environment.
85 | - Use VS Code, PyCharm, or Google Colab.
86 | - View outputs in terminal, browser (Swagger UI), and Matplotlib visualizations (PNGs).
87 | - Check terminal for errors; ensure dependencies are installed.
88 |
89 | ## 🏆 Practical Tasks
90 |
91 | 1. **Dockerizing FastAPI Apps**:
92 | - Create a Dockerfile for a FastAPI app.
93 | - Simulate running the app in a container.
94 | 2. **Cloud Deployment**:
95 | - Prepare a FastAPI app for cloud deployment.
96 | - Simulate deployment to AWS or Heroku.
97 | 3. **Scalability Metrics Visualization**:
98 | - Simulate load testing on an API.
99 | - Visualize latency and throughput metrics.
100 |
101 | ## 💡 Interview Tips
102 |
103 | - **Common Questions**:
104 | - How do you Dockerize a FastAPI application?
105 | - What are the steps to deploy a FastAPI app to AWS or Heroku?
106 | - How do you measure API scalability?
107 | - What tools do you use for load testing?
108 | - **Tips**:
109 | - Explain Dockerization with a sample `Dockerfile`.
110 | - Demonstrate cloud deployment steps (e.g., AWS Elastic Beanstalk, Heroku CLI).
111 | - Code tasks like generating scalability metrics.
112 | - Discuss trade-offs of containerization vs. serverless.
113 | - **Coding Tasks**:
114 | - Write a Dockerfile for a FastAPI app.
115 | - Simulate load testing and visualize results.
116 | - **Conceptual Clarity**:
117 | - Explain the benefits of Docker for deployment.
118 | - Describe how cloud platforms ensure scalability.
119 |
120 | ## 📚 Resources
121 |
122 | - [FastAPI Documentation](https://fastapi.tiangolo.com/)
123 | - [Docker Documentation](https://docs.docker.com/)
124 | - [AWS Elastic Beanstalk Documentation](https://docs.aws.amazon.com/elasticbeanstalk/)
125 | - [Heroku Documentation](https://devcenter.heroku.com/)
126 |
127 | ## 🤝 Contributions
128 |
129 | 1. Fork the repository.
130 | 2. Create a feature branch (`git checkout -b feature/deployment-scaling`).
131 | 3. Commit changes (`git commit -m 'Add deployment and scaling content'`).
132 | 4. Push to the branch (`git push origin feature/deployment-scaling`).
133 | 5. Open a Pull Request.
134 |
135 | ---
136 |
137 |
138 |
Happy Learning and Good Luck with Your Interviews! ✨
139 |
--------------------------------------------------------------------------------
/Fast API Interview Questions/README.md:
--------------------------------------------------------------------------------
1 | # FastAPI Interview Questions for AI/ML Roles
2 |
3 | This README provides 170 interview questions tailored for AI/ML roles, focusing on **FastAPI**, a modern, high-performance web framework for building APIs in Python. The questions cover **core concepts** (e.g., routing, middleware, Pydantic models, database integration, ML model serving, testing, deployment, and scalability) and their applications in AI/ML workflows, such as serving machine learning models, integrating with LLMs, or handling data pipelines. Questions are categorized by topic and divided into **Basic**, **Intermediate**, and **Advanced** levels to support candidates preparing for roles requiring expertise in building and deploying APIs for AI-driven applications.
4 |
5 | ## FastAPI Basics
6 |
7 | ### Basic
8 | 1. **What is FastAPI, and why is it used in AI/ML applications?**
9 | A Python framework for building fast, asynchronous APIs, ideal for serving ML models.
10 | ```python
11 | from fastapi import FastAPI
12 | app = FastAPI()
13 | @app.get("/")
14 | async def root():
15 | return {"message": "Hello, FastAPI!"}
16 | ```
17 |
18 | 2. **How do you install FastAPI and its dependencies?**
19 | Uses pip to install FastAPI and Uvicorn.
20 | ```python
21 | # Terminal command
22 | pip install fastapi uvicorn
23 | ```
24 |
25 | 3. **What is the role of Pydantic in FastAPI?**
26 | Validates and serializes data for API requests/responses.
27 | ```python
28 | from pydantic import BaseModel
29 | class Item(BaseModel):
30 | name: str
31 | price: float
32 | ```
33 |
34 | 4. **How do you run a FastAPI application?**
35 | Uses Uvicorn as the ASGI server.
36 | ```python
37 | # Terminal command
38 | uvicorn main:app --reload
39 | ```
40 |
41 | 5. **How do you define a simple GET endpoint in FastAPI?**
42 | Uses decorators for routing.
43 | ```python
44 | from fastapi import FastAPI
45 | app = FastAPI()
46 | @app.get("/items/{item_id}")
47 | async def read_item(item_id: int):
48 | return {"item_id": item_id}
49 | ```
50 |
51 | 6. **How do you visualize API response times?**
52 | Plots latency metrics.
53 | ```python
54 | import matplotlib.pyplot as plt
55 | def plot_response_times(times):
56 | plt.plot(times)
57 | plt.savefig("response_times.png")
58 | ```
59 |
60 | #### Intermediate
61 | 7. **Write a function to create a POST endpoint with Pydantic validation.**
62 | Accepts and validates JSON data.
63 | ```python
64 | from fastapi import FastAPI
65 | from pydantic import BaseModel
66 | app = FastAPI()
67 | class Item(BaseModel):
68 | name: str
69 | price: float
70 | @app.post("/items/")
71 | async def create_item(item: Item):
72 | return item
73 | ```
74 |
75 | 8. **How do you handle query parameters in FastAPI?**
76 | Defines optional parameters in endpoints.
77 | ```python
78 | from fastapi import FastAPI
79 | app = FastAPI()
80 | @app.get("/items/")
81 | async def read_items(skip: int = 0, limit: int = 10):
82 | return {"skip": skip, "limit": limit}
83 | ```
84 |
85 | 9. **Write a function to return custom responses in FastAPI.**
86 | Uses Response objects for status codes.
87 | ```python
88 | from fastapi import FastAPI, Response
89 | app = FastAPI()
90 | @app.get("/health")
91 | async def health_check():
92 | return Response(content="OK", status_code=200)
93 | ```
94 |
95 | 10. **How do you implement path parameters with type hints?**
96 | Enforces data types for parameters.
97 | ```python
98 | from fastapi import FastAPI
99 | app = FastAPI()
100 | @app.get("/users/{user_id}")
101 | async def read_user(user_id: str):
102 | return {"user_id": user_id}
103 | ```
104 |
105 | 11. **Write a function to handle file uploads in FastAPI.**
106 | Processes uploaded files.
107 | ```python
108 | from fastapi import FastAPI, File, UploadFile
109 | app = FastAPI()
110 | @app.post("/upload/")
111 | async def upload_file(file: UploadFile = File(...)):
112 | return {"filename": file.filename}
113 | ```
114 |
115 | 12. **How do you enable automatic Swagger UI in FastAPI?**
116 | Included by default at `/docs`.
117 | ```python
118 | from fastapi import FastAPI
119 | app = FastAPI(docs_url="/docs")
120 | @app.get("/")
121 | async def root():
122 | return {"message": "Visit /docs for Swagger UI"}
123 | ```
124 |
125 | #### Advanced
126 | 13. **Write a function to implement custom exception handling.**
127 | Returns custom error responses.
128 | ```python
129 | from fastapi import FastAPI, HTTPException
130 | app = FastAPI()
131 | @app.get("/items/{item_id}")
132 | async def read_item(item_id: int):
133 | if item_id < 0:
134 | raise HTTPException(status_code=400, detail="Invalid item ID")
135 | return {"item_id": item_id}
136 | ```
137 |
138 | 14. **How do you implement dependency injection in FastAPI?**
139 | Reuses logic across endpoints.
140 | ```python
141 | from fastapi import FastAPI, Depends
142 | app = FastAPI()
143 | async def get_db():
144 | return {"db": "connected"}
145 | @app.get("/data")
146 | async def read_data(db=Depends(get_db)):
147 | return db
148 | ```
149 |
150 | 15. **Write a function to implement background tasks in FastAPI.**
151 | Runs tasks asynchronously.
152 | ```python
153 | from fastapi import FastAPI, BackgroundTasks
154 | app = FastAPI()
155 | async def log_task(message: str):
156 | print(f"Logging: {message}")
157 | @app.post("/log/")
158 | async def create_log(message: str, background_tasks: BackgroundTasks):
159 | background_tasks.add_task(log_task, message)
160 | return {"status": "Task queued"}
161 | ```
162 |
163 | 16. **How do you implement WebSockets in FastAPI?**
164 | Handles real-time communication.
165 | ```python
166 | from fastapi import FastAPI, WebSocket
167 | app = FastAPI()
168 | @app.websocket("/ws")
169 | async def websocket_endpoint(websocket: WebSocket):
170 | await websocket.accept()
171 | await websocket.send_text("Connected")
172 | await websocket.close()
173 | ```
174 |
175 | 17. **Write a function to implement middleware in FastAPI.**
176 | Processes requests globally.
177 | ```python
178 | from fastapi import FastAPI
179 | app = FastAPI()
180 | @app.middleware("http")
181 | async def add_header(request, call_next):
182 | response = await call_next(request)
183 | response.headers["X-Custom-Header"] = "Value"
184 | return response
185 | ```
186 |
187 | 18. **How do you optimize FastAPI for high-concurrency?**
188 | Uses async/await and Uvicorn workers.
189 | ```python
190 | # Terminal command
191 | uvicorn main:app --workers 4 --host 0.0.0.0 --port 8000
192 | ```
193 |
194 | ## Routing and Endpoints
195 |
196 | ### Basic
197 | 19. **What is routing in FastAPI?**
198 | Maps URLs to functions.
199 | ```python
200 | from fastapi import FastAPI
201 | app = FastAPI()
202 | @app.get("/hello")
203 | async def hello():
204 | return {"message": "Hello, World!"}
205 | ```
206 |
207 | 20. **How do you define multiple HTTP methods for an endpoint?**
208 | Uses separate decorators.
209 | ```python
210 | from fastapi import FastAPI
211 | app = FastAPI()
212 | @app.get("/items/{item_id}")
213 | async def read_item(item_id: int):
214 | return {"item_id": item_id}
215 | @app.post("/items/{item_id}")
216 | async def update_item(item_id: int):
217 | return {"updated_id": item_id}
218 | ```
219 |
220 | 21. **What are path parameters in FastAPI?**
221 | Variables in URL paths.
222 | ```python
223 | from fastapi import FastAPI
224 | app = FastAPI()
225 | @app.get("/products/{product_id}")
226 | async def read_product(product_id: int):
227 | return {"product_id": product_id}
228 | ```
229 |
230 | 22. **How do you handle optional query parameters?**
231 | Uses default values.
232 | ```python
233 | from fastapi import FastAPI
234 | app = FastAPI()
235 | @app.get("/search")
236 | async def search_items(q: str | None = None):
237 | return {"query": q}
238 | ```
239 |
240 | 23. **How do you define a root endpoint in FastAPI?**
241 | Maps to `/`.
242 | ```python
243 | from fastapi import FastAPI
244 | app = FastAPI()
245 | @app.get("/")
246 | async def root():
247 | return {"message": "Welcome to FastAPI"}
248 | ```
249 |
250 | 24. **How do you visualize endpoint usage?**
251 | Plots request counts.
252 | ```python
253 | import matplotlib.pyplot as plt
254 | def plot_endpoint_usage(counts):
255 | plt.bar(counts.keys(), counts.values())
256 | plt.savefig("endpoint_usage.png")
257 | ```
258 |
259 | #### Intermediate
260 | 25. **Write a function to create nested routes.**
261 | Organizes endpoints hierarchically.
262 | ```python
263 | from fastapi import FastAPI, APIRouter
264 | app = FastAPI()
265 | router = APIRouter(prefix="/api")
266 | @router.get("/users")
267 | async def read_users():
268 | return {"users": []}
269 | app.include_router(router)
270 | ```
271 |
272 | 26. **How do you implement dynamic routing?**
273 | Uses path parameters for flexibility.
274 | ```python
275 | from fastapi import FastAPI
276 | app = FastAPI()
277 | @app.get("/{resource}/{id}")
278 | async def read_resource(resource: str, id: int):
279 | return {"resource": resource, "id": id}
280 | ```
281 |
282 | 27. **Write a function to handle route-specific middleware.**
283 | Applies logic to specific routes.
284 | ```python
285 | from fastapi import FastAPI, Request
286 | app = FastAPI()
287 | @app.middleware("http")
288 | async def log_specific_route(request: Request, call_next):
289 | if request.url.path.startswith("/admin"):
290 | print("Admin route accessed")
291 | return await call_next(request)
292 | ```
293 |
294 | 28. **How do you implement route versioning?**
295 | Uses prefixes for API versions.
296 | ```python
297 | from fastapi import FastAPI, APIRouter
298 | app = FastAPI()
299 | v1 = APIRouter(prefix="/v1")
300 | @v1.get("/items")
301 | async def read_items_v1():
302 | return {"version": "v1"}
303 | app.include_router(v1)
304 | ```
305 |
306 | 29. **Write a function to create tagged routes.**
307 | Groups endpoints in Swagger UI.
308 | ```python
309 | from fastapi import FastAPI
310 | app = FastAPI()
311 | @app.get("/items/", tags=["Items"])
312 | async def read_items():
313 | return {"items": []}
314 | ```
315 |
316 | 30. **How do you handle route conflicts in FastAPI?**
317 | Prioritizes specific routes.
318 | ```python
319 | from fastapi import FastAPI
320 | app = FastAPI()
321 | @app.get("/items/{item_id}")
322 | async def read_specific_item(item_id: int):
323 | return {"item_id": item_id}
324 | @app.get("/items/all")
325 | async def read_all_items():
326 | return {"items": "all"}
327 | ```
328 |
329 | #### Advanced
330 | 31. **Write a function to implement dynamic route generation.**
331 | Creates routes programmatically.
332 | ```python
333 | from fastapi import FastAPI
334 | app = FastAPI()
335 | def add_dynamic_route(path: str, response: dict):
336 | @app.get(path)
337 | async def dynamic_route():
338 | return response
339 | add_dynamic_route("/custom", {"message": "Dynamic route"})
340 | ```
341 |
342 | 32. **How do you implement rate limiting for routes?**
343 | Uses middleware for throttling.
344 | ```python
345 | from fastapi import FastAPI
346 | from slowapi import Limiter, _rate_limit_exceeded_handler
347 | from slowapi.util import get_remote_address
348 | app = FastAPI()
349 | limiter = Limiter(key_func=get_remote_address)
350 | app.state.limiter = limiter
351 | app.add_exception_handler(429, _rate_limit_exceeded_handler)
352 | @app.get("/limited")
353 | @limiter.limit("5/minute")
354 | async def limited_endpoint():
355 | return {"status": "OK"}
356 | ```
357 |
358 | 33. **Write a function to implement route-specific dependencies.**
359 | Applies custom logic to routes.
360 | ```python
361 | from fastapi import FastAPI, Depends
362 | app = FastAPI()
363 | async def check_role():
364 | return {"role": "admin"}
365 | @app.get("/admin", dependencies=[Depends(check_role)])
366 | async def admin_endpoint():
367 | return {"access": "granted"}
368 | ```
369 |
370 | 34. **How do you optimize route performance?**
371 | Minimizes middleware and dependencies.
372 | ```python
373 | from fastapi import FastAPI
374 | app = FastAPI()
375 | @app.get("/fast")
376 | async def fast_endpoint():
377 | return {"status": "optimized"}
378 | ```
379 |
380 | 35. **Write a function to monitor route performance.**
381 | Logs request latency.
382 | ```python
383 | import time
384 | from fastapi import FastAPI, Request
385 | app = FastAPI()
386 | @app.middleware("http")
387 | async def log_performance(request: Request, call_next):
388 | start = time.time()
389 | response = await call_next(request)
390 | print(f"Route {request.url.path} took {time.time() - start}s")
391 | return response
392 | ```
393 |
394 | 36. **How do you implement route failover?**
395 | Retries failed routes.
396 | ```python
397 | from fastapi import FastAPI
398 | from tenacity import retry, stop_after_attempt
399 | app = FastAPI()
400 | @app.get("/reliable")
401 | @retry(stop=stop_after_attempt(3))
402 | async def reliable_endpoint():
403 | return {"status": "OK"}
404 | ```
405 |
406 | ## Database Integration
407 |
408 | ### Basic
409 | 37. **How do you integrate FastAPI with SQLAlchemy?**
410 | Uses ORM for database operations.
411 | ```python
412 | from sqlalchemy import create_engine, Column, Integer, String
413 | from sqlalchemy.ext.declarative import declarative_base
414 | from sqlalchemy.orm import sessionmaker
415 | Base = declarative_base()
416 | class User(Base):
417 | __tablename__ = "users"
418 | id = Column(Integer, primary_key=True)
419 | name = Column(String)
420 | engine = create_engine("sqlite:///example.db")
421 | Base.metadata.create_all(engine)
422 | Session = sessionmaker(bind=engine)
423 | ```
424 |
425 | 38. **How do you perform CRUD operations with FastAPI?**
426 | Implements create, read, update, delete.
427 | ```python
428 | from fastapi import FastAPI
429 | app = FastAPI()
430 | @app.post("/users/")
431 | async def create_user(name: str):
432 | session = Session()
433 | user = User(name=name)
434 | session.add(user)
435 | session.commit()
436 | return {"name": name}
437 | ```
438 |
439 | 39. **What is dependency injection for database sessions?**
440 | Provides sessions to endpoints.
441 | ```python
442 | from fastapi import FastAPI, Depends
443 | app = FastAPI()
444 | def get_db():
445 | session = Session()
446 | try:
447 | yield session
448 | finally:
449 | session.close()
450 | @app.get("/users")
451 | async def read_users(db=Depends(get_db)):
452 | return db.query(User).all()
453 | ```
454 |
455 | 40. **How do you connect FastAPI to PostgreSQL?**
456 | Uses SQLAlchemy with PostgreSQL URI.
457 | ```python
458 | engine = create_engine("postgresql://user:password@localhost:5432/dbname")
459 | ```
460 |
461 | 41. **How do you handle database migrations in FastAPI?**
462 | Uses Alembic for schema changes.
463 | ```python
464 | # Terminal command
465 | alembic init migrations
466 | ```
467 |
468 | 42. **How do you visualize database query performance?**
469 | Plots query execution times.
470 | ```python
471 | import matplotlib.pyplot as plt
472 | def plot_query_times(times):
473 | plt.plot(times)
474 | plt.savefig("query_times.png")
475 | ```
476 |
477 | #### Intermediate
478 | 43. **Write a function to implement async database operations.**
479 | Uses async SQLAlchemy.
480 | ```python
481 | from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
482 | from fastapi import FastAPI
483 | app = FastAPI()
484 | engine = create_async_engine("sqlite+aiosqlite:///example.db")
485 | async def get_async_db():
486 | async with AsyncSession(engine) as session:
487 | yield session
488 | @app.get("/users")
489 | async def read_users(db=Depends(get_async_db)):
490 | return await db.execute("SELECT * FROM users").fetchall()
491 | ```
492 |
493 | 44. **How do you implement database connection pooling?**
494 | Configures SQLAlchemy for pooling.
495 | ```python
496 | engine = create_engine("sqlite:///example.db", pool_size=5, max_overflow=10)
497 | ```
498 |
499 | 45. **Write a function to handle database transactions.**
500 | Ensures atomic operations.
501 | ```python
502 | from fastapi import FastAPI, Depends
503 | app = FastAPI()
504 | @app.post("/users")
505 | async def create_user(name: str, db=Depends(get_db)):
506 | try:
507 | user = User(name=name)
508 | db.add(user)
509 | db.commit()
510 | except:
511 | db.rollback()
512 | raise
513 | return {"name": name}
514 | ```
515 |
516 | 46. **How do you integrate FastAPI with MongoDB?**
517 | Uses Motor for async MongoDB access.
518 | ```python
519 | from motor.motor_asyncio import AsyncIOMotorClient
520 | from fastapi import FastAPI
521 | app = FastAPI()
522 | client = AsyncIOMotorClient("mongodb://localhost:27017")
523 | db = client["mydb"]
524 | @app.post("/docs")
525 | async def create_doc(data: dict):
526 | result = await db["collection"].insert_one(data)
527 | return {"id": str(result.inserted_id)}
528 | ```
529 |
530 | 47. **Write a function to cache database queries.**
531 | Reduces database load.
532 | ```python
533 | from functools import lru_cache
534 | @lru_cache(maxsize=100)
535 | def cached_query(query: str):
536 | session = Session()
537 | result = session.execute(query).fetchall()
538 | session.close()
539 | return result
540 | ```
541 |
542 | 48. **How do you handle database connection errors?**
543 | Implements retries.
544 | ```python
545 | from tenacity import retry, stop_after_attempt
546 | @retry(stop=stop_after_attempt(3))
547 | def connect_db():
548 | return create_engine("sqlite:///example.db")
549 | ```
550 |
551 | #### Advanced
552 | 49. **Write a function to implement sharding in FastAPI.**
553 | Distributes data across databases.
554 | ```python
555 | from fastapi import FastAPI
556 | app = FastAPI()
557 | engines = {i: create_engine(f"sqlite:///shard_{i}.db") for i in range(3)}
558 | def get_shard_db(shard_key: int):
559 | return Session(bind=engines[shard_key % 3])
560 | @app.get("/users/{user_id}")
561 | async def read_user(user_id: int, db=Depends(get_shard_db)):
562 | return db.query(User).filter(User.id == user_id).first()
563 | ```
564 |
565 | 50. **How do you optimize database queries in FastAPI?**
566 | Uses indexing and query planning.
567 | ```python
568 | from sqlalchemy import Index
569 | Index("idx_user_name", User.name).create(bind=engine)
570 | ```
571 |
572 | 51. **Write a function to implement database failover.**
573 | Switches to backup database.
574 | ```python
575 | from fastapi import FastAPI
576 | app = FastAPI()
577 | primary_engine = create_engine("sqlite:///primary.db")
578 | backup_engine = create_engine("sqlite:///backup.db")
579 | def get_db():
580 | try:
581 | return Session(bind=primary_engine)
582 | except:
583 | return Session(bind=backup_engine)
584 | ```
585 |
586 | 52. **How do you integrate FastAPI with Redis?**
587 | Uses Redis for caching.
588 | ```python
589 | import redis.asyncio as redis
590 | from fastapi import FastAPI
591 | app = FastAPI()
592 | r = redis.Redis(host="localhost", port=6379)
593 | @app.get("/cache/{key}")
594 | async def read_cache(key: str):
595 | value = await r.get(key)
596 | return {"value": value.decode() if value else None}
597 | ```
598 |
599 | 53. **Write a function to implement database migrations programmatically.**
600 | Automates schema updates.
601 | ```python
602 | from alembic.config import Config
603 | from alembic import command
604 | def run_migrations():
605 | alembic_cfg = Config("alembic.ini")
606 | command.upgrade(alembic_cfg, "head")
607 | ```
608 |
609 | 54. **How do you monitor database performance in FastAPI?**
610 | Logs query metrics.
611 | ```python
612 | from fastapi import FastAPI, Request
613 | import time
614 | app = FastAPI()
615 | @app.middleware("http")
616 | async def log_db_performance(request: Request, call_next):
617 | start = time.time()
618 | response = await call_next(request)
619 | print(f"DB query took {time.time() - start}s")
620 | return response
621 | ```
622 |
623 | ## Serving ML Models
624 |
625 | ### Basic
626 | 55. **How do you serve a machine learning model with FastAPI?**
627 | Exposes model predictions via API.
628 | ```python
629 | from fastapi import FastAPI
630 | import joblib
631 | app = FastAPI()
632 | model = joblib.load("model.pkl")
633 | @app.post("/predict")
634 | async def predict(data: list):
635 | return {"prediction": model.predict([data]).tolist()}
636 | ```
637 |
638 | 56. **What is Pydantic for model input validation?**
639 | Ensures valid input data.
640 | ```python
641 | from pydantic import BaseModel
642 | class PredictionInput(BaseModel):
643 | features: list[float]
644 | ```
645 |
646 | 57. **How do you integrate FastAPI with scikit-learn?**
647 | Serves scikit-learn models.
648 | ```python
649 | from fastapi import FastAPI
650 | from pydantic import BaseModel
651 | import joblib
652 | app = FastAPI()
653 | model = joblib.load("sklearn_model.pkl")
654 | class Input(BaseModel):
655 | features: list[float]
656 | @app.post("/predict")
657 | async def predict(input: Input):
658 | return {"prediction": model.predict([input.features]).tolist()}
659 | ```
660 |
661 | 58. **How do you serve a PyTorch model with FastAPI?**
662 | Uses PyTorch for inference.
663 | ```python
664 | from fastapi import FastAPI
665 | import torch
666 | app = FastAPI()
667 | model = torch.load("pytorch_model.pth")
668 | model.eval()
669 | @app.post("/predict")
670 | async def predict(data: list):
671 | input_tensor = torch.tensor(data)
672 | return {"prediction": model(input_tensor).tolist()}
673 | ```
674 |
675 | 59. **How do you handle large model inputs?**
676 | Processes inputs in chunks.
677 | ```python
678 | from fastapi import FastAPI
679 | app = FastAPI()
680 | @app.post("/predict")
681 | async def predict(data: list):
682 | return {"chunked": len(data) // 100}
683 | ```
684 |
685 | 60. **How do you visualize model prediction performance?**
686 | Plots accuracy or latency.
687 | ```python
688 | import matplotlib.pyplot as plt
689 | def plot_prediction_performance(metrics):
690 | plt.plot(metrics["accuracy"])
691 | plt.savefig("prediction_performance.png")
692 | ```
693 |
694 | #### Intermediate
695 | 61. **Write a function to serve a TensorFlow model.**
696 | Uses TensorFlow for predictions.
697 | ```python
698 | from fastapi import FastAPI
699 | from pydantic import BaseModel
700 | import tensorflow as tf
701 | app = FastAPI()
702 | model = tf.keras.models.load_model("tf_model")
703 | class Input(BaseModel):
704 | features: list[float]
705 | @app.post("/predict")
706 | async def predict(input: Input):
707 | return {"prediction": model.predict([input.features]).tolist()}
708 | ```
709 |
710 | 62. **How do you implement batch predictions in FastAPI?**
711 | Processes multiple inputs.
712 | ```python
713 | from fastapi import FastAPI
714 | import joblib
715 | app = FastAPI()
716 | model = joblib.load("model.pkl")
717 | @app.post("/batch_predict")
718 | async def batch_predict(data: list[list[float]]):
719 | return {"predictions": model.predict(data).tolist()}
720 | ```
721 |
722 | 63. **Write a function to integrate FastAPI with ONNX models.**
723 | Uses ONNX runtime for inference.
724 | ```python
725 | from fastapi import FastAPI
726 | import onnxruntime as ort
727 | app = FastAPI()
728 | session = ort.InferenceSession("model.onnx")
729 | @app.post("/predict")
730 | async def predict(data: list):
731 | return {"prediction": session.run(None, {"input": data})[0].tolist()}
732 | ```
733 |
734 | 64. **How do you serve Hugging Face models with FastAPI?**
735 | Uses Transformers for NLP tasks.
736 | ```python
737 | from fastapi import FastAPI
738 | from transformers import pipeline
739 | app = FastAPI()
740 | nlp = pipeline("sentiment-analysis")
741 | @app.post("/sentiment")
742 | async def sentiment(text: str):
743 | return nlp(text)
744 | ```
745 |
746 | 65. **Write a function to cache model predictions.**
747 | Reduces inference time.
748 | ```python
749 | from functools import lru_cache
750 | @lru_cache(maxsize=1000)
751 | def cached_predict(data: str):
752 | model = joblib.load("model.pkl")
753 | return model.predict([eval(data)]).tolist()
754 | ```
755 |
756 | 66. **How do you handle model versioning in FastAPI?**
757 | Serves different model versions.
758 | ```python
759 | from fastapi import FastAPI
760 | import joblib
761 | app = FastAPI()
762 | models = {v: joblib.load(f"model_v{v}.pkl") for v in [1, 2]}
763 | @app.post("/predict/{version}")
764 | async def predict(version: int, data: list):
765 | return {"prediction": models[version].predict([data]).tolist()}
766 | ```
767 |
768 | #### Advanced
769 | 67. **Write a function to implement A/B testing for models.**
770 | Compares model performance.
771 | ```python
772 | from fastapi import FastAPI
773 | import joblib
774 | app = FastAPI()
775 | models = {"A": joblib.load("model_a.pkl"), "B": joblib.load("model_b.pkl")}
776 | @app.post("/ab_test")
777 | async def ab_test(data: list):
778 | return {
779 | "A": models["A"].predict([data]).tolist(),
780 | "B": models["B"].predict([data]).tolist()
781 | }
782 | ```
783 |
784 | 68. **How do you implement model monitoring in FastAPI?**
785 | Logs prediction metrics.
786 | ```python
787 | from fastapi import FastAPI
788 | import joblib
789 | app = FastAPI()
790 | model = joblib.load("model.pkl")
791 | @app.post("/predict")
792 | async def predict(data: list):
793 | prediction = model.predict([data]).tolist()
794 | print(f"Prediction: {prediction}")
795 | return {"prediction": prediction}
796 | ```
797 |
798 | 69. **Write a function to serve streaming model predictions.**
799 | Streams large outputs.
800 | ```python
801 | from fastapi import FastAPI
802 | from fastapi.responses import StreamingResponse
803 | app = FastAPI()
804 | model = joblib.load("model.pkl")
805 | async def stream_predictions(data: list):
806 | for chunk in data:
807 | yield str(model.predict([chunk]).tolist()) + "\n"
808 | @app.post("/stream")
809 | async def stream(data: list):
810 | return StreamingResponse(stream_predictions(data), media_type="text/plain")
811 | ```
812 |
813 | 70. **How do you optimize model inference in FastAPI?**
814 | Uses batching and async.
815 | ```python
816 | from fastapi import FastAPI
817 | import joblib
818 | app = FastAPI()
819 | model = joblib.load("model.pkl")
820 | @app.post("/optimized_predict")
821 | async def optimized_predict(data: list[list[float]]):
822 | return {"predictions": model.predict(data).tolist()}
823 | ```
824 |
825 | 71. **Write a function to integrate FastAPI with Triton Inference Server.**
826 | Serves models via Triton.
827 | ```python
828 | from fastapi import FastAPI
829 | from tritonclient.http import InferenceServerClient
830 | app = FastAPI()
831 | triton_client = InferenceServerClient("localhost:8000")
832 | @app.post("/triton_predict")
833 | async def triton_predict(data: list):
834 | inputs = triton_client.infer("model", [data])
835 | return {"prediction": inputs.as_numpy("output").tolist()}
836 | ```
837 |
838 | 72. **How do you implement model explainability in FastAPI?**
839 | Returns feature importance.
840 | ```python
841 | from fastapi import FastAPI
842 | import joblib
843 | import shap
844 | app = FastAPI()
845 | model = joblib.load("model.pkl")
846 | explainer = shap.TreeExplainer(model)
847 | @app.post("/explain")
848 | async def explain(data: list):
849 | shap_values = explainer.shap_values([data])
850 | return {"shap_values": shap_values.tolist()}
851 | ```
852 |
853 | ## Testing and Validation
854 |
855 | ### Basic
856 | 73. **How do you write unit tests for FastAPI endpoints?**
857 | Uses TestClient for testing.
858 | ```python
859 | from fastapi import FastAPI
860 | from fastapi.testclient import TestClient
861 | app = FastAPI()
862 | @app.get("/")
863 | async def root():
864 | return {"message": "Hello"}
865 | client = TestClient(app)
866 | def test_root():
867 | response = client.get("/")
868 | assert response.status_code == 200
869 | assert response.json() == {"message": "Hello"}
870 | ```
871 |
872 | 74. **What is Pydantic validation testing?**
873 | Tests input validation.
874 | ```python
875 | from pydantic import BaseModel
876 | class Item(BaseModel):
877 | name: str
878 | def test_pydantic_validation():
879 | try:
880 | Item(name=123)
881 | assert False
882 | except:
883 | assert True
884 | ```
885 |
886 | 75. **How do you test query parameters in FastAPI?**
887 | Simulates query strings.
888 | ```python
889 | from fastapi.testclient import TestClient
890 | from fastapi import FastAPI
891 | app = FastAPI()
892 | @app.get("/items")
893 | async def read_items(q: str):
894 | return {"q": q}
895 | client = TestClient(app)
896 | def test_query():
897 | response = client.get("/items?q=test")
898 | assert response.json() == {"q": "test"}
899 | ```
900 |
901 | 76. **How do you mock dependencies in FastAPI tests?**
902 | Overrides dependencies.
903 | ```python
904 | from fastapi import FastAPI, Depends
905 | from fastapi.testclient import TestClient
906 | app = FastAPI()
907 | async def get_db():
908 | return {"db": "real"}
909 | @app.get("/data")
910 | async def read_data(db=Depends(get_db)):
911 | return db
912 | client = TestClient(app)
913 | def test_mock_db():
914 | app.dependency_overrides[get_db] = lambda: {"db": "mock"}
915 | response = client.get("/data")
916 | assert response.json() == {"db": "mock"}
917 | ```
918 |
919 | 77. **How do you test error handling in FastAPI?**
920 | Simulates error conditions.
921 | ```python
922 | from fastapi import FastAPI, HTTPException
923 | from fastapi.testclient import TestClient
924 | app = FastAPI()
925 | @app.get("/items/{item_id}")
926 | async def read_item(item_id: int):
927 | if item_id < 0:
928 | raise HTTPException(status_code=400, detail="Invalid ID")
929 | return {"item_id": item_id}
930 | client = TestClient(app)
931 | def test_error():
932 | response = client.get("/items/-1")
933 | assert response.status_code == 400
934 | ```
935 |
936 | 78. **How do you visualize test coverage?**
937 | Plots coverage metrics.
938 | ```python
939 | import matplotlib.pyplot as plt
940 | def plot_test_coverage(coverage):
941 | plt.bar(["Covered", "Uncovered"], [coverage, 100 - coverage])
942 | plt.savefig("test_coverage.png")
943 | ```
944 |
945 | #### Intermediate
946 | 79. **Write a function to test async endpoints.**
947 | Tests asynchronous routes.
948 | ```python
949 | from fastapi import FastAPI
950 | from fastapi.testclient import TestClient
951 | app = FastAPI()
952 | @app.get("/async")
953 | async def async_endpoint():
954 | return {"status": "async"}
955 | client = TestClient(app)
956 | def test_async():
957 | response = client.get("/async")
958 | assert response.status_code == 200
959 | assert response.json() == {"status": "async"}
960 | ```
961 |
962 | 80. **How do you implement integration tests for FastAPI?**
963 | Tests multiple components.
964 | ```python
965 | from fastapi import FastAPI, Depends
966 | from fastapi.testclient import TestClient
967 | app = FastAPI()
968 | def get_db():
969 | return {"db": "connected"}
970 | @app.get("/data")
971 | async def read_data(db=Depends(get_db)):
972 | return db
973 | client = TestClient(app)
974 | def test_integration():
975 | response = client.get("/data")
976 | assert response.json() == {"db": "connected"}
977 | ```
978 |
979 | 81. **Write a function to test WebSocket endpoints.**
980 | Simulates WebSocket connections.
981 | ```python
982 | from fastapi import FastAPI, WebSocket
983 | from starlette.testclient import TestClient
984 | app = FastAPI()
985 | @app.websocket("/ws")
986 | async def websocket_endpoint(websocket: WebSocket):
987 | await websocket.accept()
988 | await websocket.send_text("Test")
989 | await websocket.close()
990 | client = TestClient(app)
991 | def test_websocket():
992 | with client.websocket_connect("/ws") as ws:
993 | assert ws.receive_text() == "Test"
994 | ```
995 |
996 | 82. **How do you test middleware in FastAPI?**
997 | Verifies middleware behavior.
998 | ```python
999 | from fastapi import FastAPI, Request
1000 | from fastapi.testclient import TestClient
1001 | app = FastAPI()
1002 | @app.middleware("http")
1003 | async def add_header(request: Request, call_next):
1004 | response = await call_next(request)
1005 | response.headers["X-Test"] = "Value"
1006 | return response
1007 | @app.get("/")
1008 | async def root():
1009 | return {"message": "Hello"}
1010 | client = TestClient(app)
1011 | def test_middleware():
1012 | response = client.get("/")
1013 | assert response.headers["X-Test"] == "Value"
1014 | ```
1015 |
1016 | 83. **Write a function to test database interactions.**
1017 | Tests CRUD operations.
1018 | ```python
1019 | from fastapi import FastAPI, Depends
1020 | from fastapi.testclient import TestClient
1021 | app = FastAPI()
1022 | def get_db():
1023 | return Session()
1024 | @app.post("/users")
1025 | async def create_user(name: str, db=Depends(get_db)):
1026 | user = User(name=name)
1027 | db.add(user)
1028 | db.commit()
1029 | return {"name": name}
1030 | client = TestClient(app)
1031 | def test_db():
1032 | response = client.post("/users", json={"name": "Test"})
1033 | assert response.json() == {"name": "Test"}
1034 | ```
1035 |
1036 | 84. **How do you implement load testing for FastAPI?**
1037 | Simulates high traffic.
1038 | ```python
1039 | from locust import HttpUser, task
1040 | class FastAPIUser(HttpUser):
1041 | host = "http://localhost:8000"
1042 | @task
1043 | def test_endpoint(self):
1044 | self.client.get("/")
1045 | ```
1046 |
1047 | #### Advanced
1048 | 85. **Write a function to implement end-to-end testing.**
1049 | Tests full API workflows.
1050 | ```python
1051 | from fastapi import FastAPI
1052 | from fastapi.testclient import TestClient
1053 | app = FastAPI()
1054 | @app.post("/items")
1055 | async def create_item(name: str):
1056 | return {"name": name}
1057 | @app.get("/items/{name}")
1058 | async def read_item(name: str):
1059 | return {"name": name}
1060 | client = TestClient(app)
1061 | def test_e2e():
1062 | create_response = client.post("/items", json={"name": "Test"})
1063 | read_response = client.get("/items/Test")
1064 | assert create_response.json() == read_response.json()
1065 | ```
1066 |
1067 | 86. **How do you implement fuzz testing for FastAPI?**
1068 | Tests with random inputs.
1069 | ```python
1070 | from fastapi.testclient import TestClient
1071 | from hypothesis import given
1072 | from hypothesis.strategies import text
1073 | app = FastAPI()
1074 | @app.get("/echo/{value}")
1075 | async def echo(value: str):
1076 | return {"value": value}
1077 | client = TestClient(app)
1078 | @given(text())
1079 | def test_fuzz(value):
1080 | response = client.get(f"/echo/{value}")
1081 | assert response.status_code == 200
1082 | ```
1083 |
1084 | 87. **Write a function to test API versioning.**
1085 | Verifies versioned endpoints.
1086 | ```python
1087 | from fastapi import FastAPI, APIRouter
1088 | from fastapi.testclient import TestClient
1089 | app = FastAPI()
1090 | v1 = APIRouter(prefix="/v1")
1091 | @v1.get("/items")
1092 | async def read_items_v1():
1093 | return {"version": "v1"}
1094 | app.include_router(v1)
1095 | client = TestClient(app)
1096 | def test_versioning():
1097 | response = client.get("/v1/items")
1098 | assert response.json() == {"version": "v1"}
1099 | ```
1100 |
1101 | 88. **How do you test rate limiting in FastAPI?**
1102 | Simulates excessive requests.
1103 | ```python
1104 | from fastapi import FastAPI
1105 | from fastapi.testclient import TestClient
1106 | from slowapi import Limiter
1107 | app = FastAPI()
1108 | limiter = Limiter(key_func=lambda: "test")
1109 | app.state.limiter = limiter
1110 | @app.get("/limited")
1111 | @limiter.limit("1/second")
1112 | async def limited():
1113 | return {"status": "OK"}
1114 | client = TestClient(app)
1115 | def test_rate_limit():
1116 | response1 = client.get("/limited")
1117 | response2 = client.get("/limited")
1118 | assert response2.status_code == 429
1119 | ```
1120 |
1121 | 89. **Write a function to test dependency injection.**
1122 | Verifies dependency behavior.
1123 | ```python
1124 | from fastapi import FastAPI, Depends
1125 | from fastapi.testclient import TestClient
1126 | app = FastAPI()
1127 | async def get_token():
1128 | return "test_token"
1129 | @app.get("/secure")
1130 | async def secure_endpoint(token=Depends(get_token)):
1131 | return {"token": token}
1132 | client = TestClient(app)
1133 | def test_dependency():
1134 | response = client.get("/secure")
1135 | assert response.json() == {"token": "test_token"}
1136 | ```
1137 |
1138 | 90. **How do you implement performance testing for FastAPI?**
1139 | Measures throughput and latency.
1140 | ```python
1141 | import time
1142 | from fastapi.testclient import TestClient
1143 | app = FastAPI()
1144 | @app.get("/")
1145 | async def root():
1146 | return {"message": "Hello"}
1147 | client = TestClient(app)
1148 | def test_performance():
1149 | start = time.time()
1150 | for _ in range(100):
1151 | client.get("/")
1152 | print(f"Average latency: {(time.time() - start) / 100}s")
1153 | ```
1154 |
1155 | ## Deployment and Scalability
1156 |
1157 | ### Basic
1158 | 91. **How do you deploy a FastAPI application with Docker?**
1159 | Containerizes the app.
1160 | ```python
1161 | # Dockerfile
1162 | FROM python:3.9
1163 | WORKDIR /app
1164 | COPY . .
1165 | RUN pip install fastapi uvicorn
1166 | CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
1167 | ```
1168 |
1169 | 92. **How do you configure Uvicorn for production?**
1170 | Sets workers and logging.
1171 | ```python
1172 | # Terminal command
1173 | uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 --log-level info
1174 | ```
1175 |
1176 | 93. **What is environment configuration in FastAPI?**
1177 | Uses environment variables.
1178 | ```python
1179 | import os
1180 | from fastapi import FastAPI
1181 | app = FastAPI()
1182 | @app.get("/")
1183 | async def root():
1184 | return {"env": os.getenv("ENV", "dev")}
1185 | ```
1186 |
1187 | 94. **How do you enable CORS in FastAPI?**
1188 | Allows cross-origin requests.
1189 | ```python
1190 | from fastapi import FastAPI
1191 | from fastapi.middleware.cors import CORSMiddleware
1192 | app = FastAPI()
1193 | app.add_middleware(
1194 | CORSMiddleware,
1195 | allow_origins=["*"],
1196 | allow_methods=["*"],
1197 | allow_headers=["*"],
1198 | )
1199 | ```
1200 |
1201 | 95. **How do you deploy FastAPI to AWS Lambda?**
1202 | Uses Mangum for ASGI.
1203 | ```python
1204 | from fastapi import FastAPI
1205 | from mangum import Mangum
1206 | app = FastAPI()
1207 | @app.get("/")
1208 | async def root():
1209 | return {"message": "Hello"}
1210 | handler = Mangum(app)
1211 | ```
1212 |
1213 | 96. **How do you visualize deployment metrics?**
1214 | Plots latency and throughput.
1215 | ```python
1216 | import matplotlib.pyplot as plt
1217 | def plot_deployment_metrics(metrics):
1218 | plt.plot(metrics["latency"], label="Latency")
1219 | plt.plot(metrics["throughput"], label="Throughput")
1220 | plt.legend()
1221 | plt.savefig("deployment_metrics.png")
1222 | ```
1223 |
1224 | #### Intermediate
1225 | 97. **Write a function to deploy FastAPI with Kubernetes.**
1226 | Defines Kubernetes manifests.
1227 | ```python
1228 | from kubernetes import client, config
1229 | def deploy_fastapi():
1230 | config.load_kube_config()
1231 | v1 = client.CoreV1Api()
1232 | service = client.V1Service(
1233 | metadata=client.V1ObjectMeta(name="fastapi-service"),
1234 | spec=client.V1ServiceSpec(
1235 | selector={"app": "fastapi"},
1236 | ports=[client.V1ServicePort(port=80)]
1237 | )
1238 | )
1239 | v1.create_namespaced_service(namespace="default", body=service)
1240 | ```
1241 |
1242 | 98. **How do you implement load balancing in FastAPI?**
1243 | Uses nginx or Kubernetes.
1244 | ```python
1245 | # nginx.conf snippet
1246 | upstream fastapi {
1247 | server 127.0.0.1:8000;
1248 | server 127.0.0.1:8001;
1249 | }
1250 | ```
1251 |
1252 | 99. **Write a function to monitor FastAPI performance.**
1253 | Logs request metrics.
1254 | ```python
1255 | from fastapi import FastAPI, Request
1256 | import time
1257 | app = FastAPI()
1258 | @app.middleware("http")
1259 | async def monitor_performance(request: Request, call_next):
1260 | start = time.time()
1261 | response = await call_next(request)
1262 | print(f"Request took {time.time() - start}s")
1263 | return response
1264 | ```
1265 |
1266 | 100. **How do you implement auto-scaling for FastAPI?**
1267 | Uses Kubernetes HPA.
1268 | ```python
1269 | from kubernetes import client, config
1270 | def create_hpa():
1271 | config.load_kube_config()
1272 | v1 = client.AutoscalingV1Api()
1273 | hpa = client.V1HorizontalPodAutoscaler(
1274 | metadata=client.V1ObjectMeta(name="fastapi-hpa"),
1275 | spec=client.V1HorizontalPodAutoscalerSpec(
1276 | scale_target_ref=client.V1CrossVersionObjectReference(
1277 | kind="Deployment", name="fastapi", api_version="apps/v1"
1278 | ),
1279 | min_replicas=1,
1280 | max_replicas=10,
1281 | target_cpu_utilization_percentage=80
1282 | )
1283 | )
1284 | v1.create_namespaced_horizontal_pod_autoscaler(namespace="default", body=hpa)
1285 | ```
1286 |
1287 | 101. **Write a function to handle graceful shutdown.**
1288 | Ensures clean termination.
1289 | ```python
1290 | from fastapi import FastAPI
1291 | import asyncio
1292 | app = FastAPI()
1293 | @app.on_event("shutdown")
1294 | async def shutdown_event():
1295 | print("Shutting down...")
1296 | await asyncio.sleep(1)
1297 | ```
1298 |
1299 | 102. **How do you implement health checks in FastAPI?**
1300 | Exposes health endpoints.
1301 | ```python
1302 | from fastapi import FastAPI
1303 | app = FastAPI()
1304 | @app.get("/health")
1305 | async def health_check():
1306 | return {"status": "healthy"}
1307 | ```
1308 |
1309 | #### Advanced
1310 | 103. **Write a function to implement blue-green deployment.**
1311 | Switches between app versions.
1312 | ```python
1313 | from kubernetes import client, config
1314 | def blue_green_deploy(version: str):
1315 | config.load_kube_config()
1316 | v1 = client.CoreV1Api()
1317 | service = client.V1Service(
1318 | metadata=client.V1ObjectMeta(name="fastapi-service"),
1319 | spec=client.V1ServiceSpec(
1320 | selector={"app": f"fastapi-{version}"},
1321 | ports=[client.V1ServicePort(port=80)]
1322 | )
1323 | )
1324 | v1.replace_namespaced_service(name="fastapi-service", namespace="default", body=service)
1325 | ```
1326 |
1327 | 104. **How do you integrate FastAPI with Prometheus?**
1328 | Exposes metrics for monitoring.
1329 | ```python
1330 | from fastapi import FastAPI
1331 | from prometheus_fastapi_instrumentator import Instrumentator
1332 | app = FastAPI()
1333 | Instrumentator().instrument(app).expose(app)
1334 | @app.get("/")
1335 | async def root():
1336 | return {"message": "Hello"}
1337 | ```
1338 |
1339 | 105. **Write a function to implement canary releases.**
1340 | Tests new versions gradually.
1341 | ```python
1342 | from kubernetes import client, config
1343 | def canary_release():
1344 | config.load_kube_config()
1345 | v1 = client.AppsV1Api()
1346 | deployment = client.V1Deployment(
1347 | metadata=client.V1ObjectMeta(name="fastapi-canary"),
1348 | spec=client.V1DeploymentSpec(
1349 | replicas=1,
1350 | selector=client.V1LabelSelector(match_labels={"app": "fastapi-canary"}),
1351 | template=client.V1PodTemplateSpec(
1352 | metadata=client.V1ObjectMeta(labels={"app": "fastapi-canary"}),
1353 | spec=client.V1PodSpec(containers=[client.V1Container(name="fastapi", image="fastapi:latest")])
1354 | )
1355 | )
1356 | )
1357 | v1.create_namespaced_deployment(namespace="default", body=deployment)
1358 | ```
1359 |
1360 | 106. **How do you optimize FastAPI for low-latency?**
1361 | Uses async and caching.
1362 | ```python
1363 | from fastapi import FastAPI
1364 | import redis.asyncio as redis
1365 | app = FastAPI()
1366 | r = redis.Redis(host="localhost", port=6379)
1367 | @app.get("/cached")
1368 | async def cached_endpoint(key: str):
1369 | value = await r.get(key)
1370 | if value:
1371 | return {"value": value.decode()}
1372 | return {"value": "computed"}
1373 | ```
1374 |
1375 | 107. **Write a function to implement distributed tracing.**
1376 | Tracks request flow.
1377 | ```python
1378 | from fastapi import FastAPI
1379 | from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
1380 | app = FastAPI()
1381 | FastAPIInstrumentor.instrument_app(app)
1382 | @app.get("/")
1383 | async def root():
1384 | return {"message": "Traced"}
1385 | ```
1386 |
1387 | 108. **How do you handle failover in FastAPI deployments?**
1388 | Uses multiple replicas.
1389 | ```python
1390 | from kubernetes import client, config
1391 | def ensure_replicas():
1392 | config.load_kube_config()
1393 | v1 = client.AppsV1Api()
1394 | deployment = client.V1Deployment(
1395 | metadata=client.V1ObjectMeta(name="fastapi"),
1396 | spec=client.V1DeploymentSpec(replicas=3, selector=client.V1LabelSelector(match_labels={"app": "fastapi"}))
1397 | )
1398 | v1.create_namespaced_deployment(namespace="default", body=deployment)
1399 | ```
1400 |
1401 | ## Security
1402 |
1403 | ### Basic
1404 | 109. **How do you implement authentication in FastAPI?**
1405 | Uses OAuth2 or JWT.
1406 | ```python
1407 | from fastapi import FastAPI, Depends
1408 | from fastapi.security import OAuth2PasswordBearer
1409 | app = FastAPI()
1410 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
1411 | @app.get("/secure")
1412 | async def secure_endpoint(token=Depends(oauth2_scheme)):
1413 | return {"token": token}
1414 | ```
1415 |
1416 | 110. **What is input validation in FastAPI?**
1417 | Uses Pydantic to validate data.
1418 | ```python
1419 | from pydantic import BaseModel
1420 | class User(BaseModel):
1421 | username: str
1422 | age: int
1423 | ```
1424 |
1425 | 111. **How do you enable HTTPS in FastAPI?**
1426 | Configures SSL with Uvicorn.
1427 | ```python
1428 | # Terminal command
1429 | uvicorn main:app --ssl-keyfile=key.pem --ssl-certfile=cert.pem
1430 | ```
1431 |
1432 | 112. **How do you prevent SQL injection in FastAPI?**
1433 | Uses parameterized queries.
1434 | ```python
1435 | from sqlalchemy.orm import Session
1436 | def get_user(db: Session, user_id: int):
1437 | return db.query(User).filter(User.id == user_id).first()
1438 | ```
1439 |
1440 | 113. **How do you secure sensitive environment variables?**
1441 | Uses python-dotenv.
1442 | ```python
1443 | from dotenv import load_dotenv
1444 | import os
1445 | load_dotenv()
1446 | API_KEY = os.getenv("API_KEY")
1447 | ```
1448 |
1449 | 114. **How do you visualize security metrics?**
1450 | Plots authentication failures.
1451 | ```python
1452 | import matplotlib.pyplot as plt
1453 | def plot_security_metrics(failures):
1454 | plt.plot(failures)
1455 | plt.savefig("security_metrics.png")
1456 | ```
1457 |
1458 | #### Intermediate
1459 | 115. **Write a function to implement JWT authentication.**
1460 | Verifies JWT tokens.
1461 | ```python
1462 | from fastapi import FastAPI, Depends, HTTPException
1463 | from jose import JWTError, jwt
1464 | app = FastAPI()
1465 | SECRET_KEY = "secret"
1466 | async def verify_token(token: str = Depends(OAuth2PasswordBearer(tokenUrl="token"))):
1467 | try:
1468 | payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
1469 | return payload
1470 | except JWTError:
1471 | raise HTTPException(status_code=401, detail="Invalid token")
1472 | @app.get("/secure")
1473 | async def secure_endpoint(payload=Depends(verify_token)):
1474 | return {"user": payload}
1475 | ```
1476 |
1477 | 116. **How do you implement role-based access control?**
1478 | Checks user roles.
1479 | ```python
1480 | from fastapi import FastAPI, Depends, HTTPException
1481 | app = FastAPI()
1482 | async def check_role(token: str = Depends(OAuth2PasswordBearer(tokenUrl="token"))):
1483 | if token != "admin":
1484 | raise HTTPException(status_code=403, detail="Forbidden")
1485 | return token
1486 | @app.get("/admin")
1487 | async def admin_endpoint(token=Depends(check_role)):
1488 | return {"access": "admin"}
1489 | ```
1490 |
1491 | 117. **Write a function to prevent CSRF attacks.**
1492 | Uses CSRF tokens.
1493 | ```python
1494 | from fastapi import FastAPI, Request, HTTPException
1495 | app = FastAPI()
1496 | @app.post("/action")
1497 | async def action(request: Request):
1498 | token = request.headers.get("X-CSRF-Token")
1499 | if not token or token != "valid_token":
1500 | raise HTTPException(status_code=403, detail="Invalid CSRF token")
1501 | return {"status": "OK"}
1502 | ```
1503 |
1504 | 118. **How do you implement rate limiting for security?**
1505 | Limits request frequency.
1506 | ```python
1507 | from fastapi import FastAPI
1508 | from slowapi import Limiter
1509 | app = FastAPI()
1510 | limiter = Limiter(key_func=lambda: "user")
1511 | app.state.limiter = limiter
1512 | @app.get("/secure")
1513 | @limiter.limit("10/minute")
1514 | async def secure_endpoint():
1515 | return {"status": "OK"}
1516 | ```
1517 |
1518 | 119. **Write a function to log security events.**
1519 | Tracks unauthorized access.
1520 | ```python
1521 | import logging
1522 | from fastapi import FastAPI, HTTPException
1523 | app = FastAPI()
1524 | logging.basicConfig(filename="security.log", level=logging.INFO)
1525 | @app.get("/secure")
1526 | async def secure_endpoint():
1527 | try:
1528 | raise HTTPException(status_code=401, detail="Unauthorized")
1529 | except HTTPException as e:
1530 | logging.error(f"Security event: {e.detail}")
1531 | raise
1532 | ```
1533 |
1534 | 120. **How do you secure WebSocket endpoints?**
1535 | Validates tokens.
1536 | ```python
1537 | from fastapi import FastAPI, WebSocket, HTTPException
1538 | app = FastAPI()
1539 | @app.websocket("/ws")
1540 | async def websocket_endpoint(websocket: WebSocket):
1541 | await websocket.accept()
1542 | token = await websocket.receive_text()
1543 | if token != "valid_token":
1544 | await websocket.close(code=1008)
1545 | return
1546 | await websocket.send_text("Authenticated")
1547 | ```
1548 |
1549 | #### Advanced
1550 | 121. **Write a function to implement API key authentication.**
1551 | Verifies API keys.
1552 | ```python
1553 | from fastapi import FastAPI, Depends, HTTPException
1554 | from fastapi.security import APIKeyHeader
1555 | app = FastAPI()
1556 | api_key_header = APIKeyHeader(name="X-API-Key")
1557 | async def verify_api_key(api_key: str = Depends(api_key_header)):
1558 | if api_key != "secret_key":
1559 | raise HTTPException(status_code=401, detail="Invalid API key")
1560 | return api_key
1561 | @app.get("/secure")
1562 | async def secure_endpoint(api_key=Depends(verify_api_key)):
1563 | return {"status": "Authenticated"}
1564 | ```
1565 |
1566 | 122. **How do you implement encryption for sensitive data?**
1567 | Uses Fernet for encryption.
1568 | ```python
1569 | from cryptography.fernet import Fernet
1570 | key = Fernet.generate_key()
1571 | f = Fernet(key)
1572 | def encrypt_data(data: str):
1573 | return f.encrypt(data.encode()).decode()
1574 | ```
1575 |
1576 | 123. **Write a function to detect injection attacks.**
1577 | Sanitizes inputs.
1578 | ```python
1579 | from fastapi import FastAPI, HTTPException
1580 | app = FastAPI()
1581 | def sanitize_input(input: str):
1582 | if any(c in input for c in [";", "--", "