Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
1,140 changes: 1,088 additions & 52 deletions TP1/1 - Practical number 1.ipynb

Large diffs are not rendered by default.

Binary file added TP2 and 3/.DS_Store
Binary file not shown.
10 changes: 10 additions & 0 deletions TP2 and 3/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
venv/
*.pyc
__pycache__/
.env
src/data/
src/models/
credentials.json
serviceAccountKey.json
.json

96 changes: 26 additions & 70 deletions TP2 and 3/README.md
Original file line number Diff line number Diff line change
@@ -1,84 +1,40 @@
# EPF-API-TP

- **Question 1:** _Which Python library/framework is often used to create fast, simple REST APIs?_
Here are the answers to your quiz questions based on the context provided, along with explanations for each choice:

- Django
### Answers to Quiz Questions

- Flask
1. **Which Python library/framework is often used to create fast, simple REST APIs?**
- **Answer:** FastAPI
- **Explanation:** FastAPI is specifically designed for building APIs quickly and efficiently, leveraging Python type hints for automatic data validation and documentation. While Django and Flask can also be used to create APIs, FastAPI is known for its speed and performance.

- FastAPI
2. **What's the main difference between Django, Flask, and FastAPI in terms of performance and speed?**
- **Answer:** FastAPI is renowned for its increased speed and performance compared with Django and Flask.
- **Explanation:** FastAPI is built on asynchronous capabilities which allow it to handle many requests concurrently, making it faster than both Django (which is synchronous) and Flask (which can be synchronous or asynchronous but is generally slower).

- All of the above
3. **What is an endpoint in the context of REST APIs?**
- **Answer:** A specific URL to which a request can be sent to interact with the API.
- **Explanation:** An endpoint is a URL that represents a resource or action in an API. Clients send requests to these URLs to perform operations like retrieving or modifying data.

- **Question 2:** _What's the main difference between Django, Flask and FastAPI in terms of performance and speed?_
4. **What are the main HTTP verbs used to define REST API methods?**
- **Answer:** GET, POST, PUT, PATCH, DELETE
- **Explanation:** These verbs correspond to the CRUD operations (Create, Read, Update, Delete) commonly used in RESTful APIs.

- Django is generally faster than Flask and FastAPI.
5. **In the context of REST APIs, what does the term "middleware" mean?**
- **Answer:** Intermediate software that processes the request before it reaches the main application.
- **Explanation:** Middleware functions as a bridge between different applications or services, processing requests and responses as they pass through.

- Flask outperforms Django and FastAPI.
6. **Which Python library is often used to serialize and deserialize JSON data in the context of REST APIs?**
- **Answer:** json.dumps() and json.loads()
- **Explanation:** The built-in `json` module in Python provides `dumps()` for converting Python objects to JSON strings and `loads()` for converting JSON strings back into Python objects.

- FastAPI is renowned for its increased speed and performance compared with Django and Flask.
7. **What is the main use of the HTTP "PUT" method in the context of REST APIs?**
- **Answer:** Update an existing resource, or create one if it doesn't exist.
- **Explanation:** The PUT method is typically used to update resources at a specific URL. If no resource exists at that URL, it can also create one.

- Django, Flask and FastAPI have equivalent performance.

- **Question 3:** What is an endpoint in the context of REST APIs?\*

- A unique IP address associated with an API.

- A breakpoint in the code where the API can be interrupted.

- A specific URL to which a request can be sent to interact with the API.

- A unique identifier assigned to each incoming request.

- **Question 4:** _What are the main HTTP verbs used to define REST API methods?_

- GET, POST, PUT, PATCH, DELETE

- SEND, RECEIVE, UPDATE, REMOVE

- READ, WRITE, MODIFY, DELETE

- FETCH, INSERT, UPDATE, DELETE

- **Question 5:** _In the context of REST APIs, what does the term "middleware" mean?_

- A component that processes data sent by the user.

- An external library used to speed up API development.

- Intermediate software that processes the request before it reaches the main application.

- A method for securing data stored in the database.

- **Question 6:** _Which Python library is often used to serialize and deserialize JSON data in the context of REST APIs?_

- JSONify

- PyJSON

- json.dumps() and json.loads()

- serializeJSON

- **Question 7:** _What is the main use of the HTTP "PUT" method in the context of REST APIs?_

- Create a new resource.

- Update an existing resource, or create one if it doesn't exist.

- Delete a resource.

- Read a specific resource.

- **Question 8:** In FastAPI, how do you define an endpoint to handle a POST request with JSON data?\*

- @app.post("/endpoint")

- @app.get("/endpoint")

- @app.request("/endpoint")

- @app.update("/endpoint")
8. **In FastAPI, how do you define an endpoint to handle a POST request with JSON data?**
- **Answer:** @app.post("/endpoint")
- **Explanation:** This decorator specifies that the function below it will handle POST requests sent to the specified endpoint.

# Creating an API with FastAPI

Expand Down
Binary file added TP2 and 3/config/.DS_Store
Binary file not shown.
7 changes: 7 additions & 0 deletions TP2 and 3/config/dev/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"ENV_NAME": "development",
"DEBUG": true,
"DATABASE_URI": "sqlite:///dev.db",
"API_URL": "http://localhost:8080"
}

7 changes: 7 additions & 0 deletions TP2 and 3/config/prd/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"ENV_NAME": "production",
"DEBUG": false,
"DATABASE_URI": "postgresql://user:password@prod-db:5432/app",
"API_URL": "https://api.myapp.com"
}

Binary file added TP2 and 3/services/.DS_Store
Binary file not shown.
10 changes: 10 additions & 0 deletions TP2 and 3/services/epf-flower-data-science/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
venv/
*.pyc
__pycache__/
.env
src/data/
src/models/
credentials.json
serviceAccountKey.json


10 changes: 8 additions & 2 deletions TP2 and 3/services/epf-flower-data-science/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import os
import uvicorn

from src.app import get_application

# Set the path to kaggle.json explicitly
kaggle_json_path = os.path.join(os.path.dirname(__file__), "kaggle.json")

# Set the environment variable for the Kaggle API to the directory of kaggle.json
os.environ['KAGGLE_CONFIG_DIR'] = os.path.dirname(kaggle_json_path)

app = get_application()

if __name__ == "__main__":
uvicorn.run("main:app", debug=True, reload=True, port=8080)
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
2 changes: 2 additions & 0 deletions TP2 and 3/services/epf-flower-data-science/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ fastapi-utils==0.2.1
pydantic==1.10
opendatasets
pytest
firebase-admin

3 changes: 3 additions & 0 deletions TP2 and 3/services/epf-flower-data-science/src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from src.services.parameters import get_parameters, update_parameters

__all__ = ['get_parameters', 'update_parameters']
File renamed without changes.
13 changes: 11 additions & 2 deletions TP2 and 3/services/epf-flower-data-science/src/api/router.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
"""API Router for Fast API."""
from fastapi import APIRouter

from .routes import parameters
from fastapi.responses import RedirectResponse
from src.api.routes import hello
from src.api.routes import data
from .routes import authentication

router = APIRouter()

@router.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/docs")

router.include_router(hello.router, tags=["Hello"])
router.include_router(data.router, prefix="/data", tags=["Dataset"])
router.include_router(parameters.router, tags=["parameters"])
router.include_router(authentication.router, tags=["authentication"])
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@

from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from firebase_admin import auth, credentials, initialize_app
from typing import List
from pathlib import Path
import firebase_admin

router = APIRouter()

# Initialize Firebase Admin SDK if not already initialized
if not firebase_admin._apps:
cred_path = Path(__file__).parent.parent.parent / "config" / "serviceAccountKey.json"
cred = credentials.Certificate(str(cred_path))
firebase_admin.initialize_app(cred, {
'projectId': 'myproject-0412025',
'authDomain': 'myproject-0412025-94c7f.firebaseapp.com',
})


#oauth2_scheme = OAuth2PasswordBearer(tokenUrl="https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword")
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="https://myproject-0412025-94c7f.firebaseapp.com/__/auth/action"
)


@router.post("/register")
async def register_user(email: str, password: str):
try:
user = auth.create_user(
email=email,
password=password,
email_verified=False,
disabled=False
)
# Send email verification
verification_link = auth.generate_email_verification_link(email)
# You'll need to implement email sending here
return {
"message": f"User {email} created successfully. Please check your email for verification.",
"uid": user.uid
}
except auth.EmailAlreadyExistsError:
raise HTTPException(status_code=400, detail="Email already exists")
except Exception as e:
raise HTTPException(status_code=400, detail="Failed to register user. Please contact support.")


@router.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
try:
user = auth.get_user_by_email(form_data.username)
custom_token = auth.create_custom_token(user.uid)
return {
"access_token": custom_token,
"token_type": "bearer",
"uid": user.uid
}
except auth.UserNotFoundError:
raise HTTPException(status_code=401, detail="User not found")
except Exception as e:
raise HTTPException(status_code=401, detail="Invalid credentials")

@router.post("/logout")
async def logout(token: str = Depends(oauth2_scheme)):
try:
decoded_token = auth.verify_id_token(token)
auth.revoke_refresh_tokens(decoded_token['uid'])
return {"message": "Successfully logged out"}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))


Loading