2
2
from sqlalchemy .orm import Session
3
3
from fastapi import Depends , HTTPException , status , APIRouter , Response
4
4
from .database import get_db
5
+ import requests
6
+ import os
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv ()
5
10
6
11
router = APIRouter ()
7
12
@@ -14,14 +19,57 @@ def get_notes(db: Session = Depends(get_db), limit: int = 10, page: int = 1, sea
14
19
models .Note .title .contains (search )).limit (limit ).offset (skip ).all ()
15
20
return {'status' : 'success' , 'results' : len (notes ), 'notes' : notes }
16
21
17
-
18
22
@router .post ('/' , status_code = status .HTTP_201_CREATED )
19
23
def create_note (payload : schemas .NoteBaseSchema , db : Session = Depends (get_db )):
20
- new_note = models .Note (** payload .dict ())
21
- db .add (new_note )
22
- db .commit ()
23
- db .refresh (new_note )
24
- return {"status" : "success" , "note" : new_note }
24
+ try :
25
+ # Get the API key
26
+ api_key = os .getenv ("api_key" )
27
+ if not api_key :
28
+ raise HTTPException (status_code = 500 , detail = "API key not configured" )
29
+
30
+ # Build the API URL
31
+ url = (
32
+ "https://api.coingecko.com/api/v3/simple/token_price/ethereum"
33
+ "?contract_addresses=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
34
+ f"&vs_currencies=usd&x_cg_demo_api_key={ api_key } "
35
+ )
36
+
37
+ # Make the request to get the crypto price
38
+ response = requests .get (url )
39
+ if response .status_code != 200 :
40
+ raise HTTPException (status_code = response .status_code , detail = "API call failed" )
41
+
42
+ data = response .json ()
43
+ price = data .get ("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" , {}).get ("usd" )
44
+
45
+ if price is None :
46
+ raise HTTPException (status_code = 500 , detail = "Invalid response from crypto API" )
47
+
48
+ # Create the note with the title from the payload and content as the crypto price
49
+ new_note = models .Note (
50
+ title = payload .title ,
51
+ content = f"Current ETH token price (USD): { price } " ,
52
+ category = payload .category ,
53
+ published = payload .published
54
+ )
55
+
56
+ db .add (new_note )
57
+ db .commit ()
58
+ db .refresh (new_note )
59
+
60
+ return {"status" : "success" , "note" : new_note }
61
+
62
+ except Exception as e :
63
+ raise HTTPException (status_code = 500 , detail = str (e ))
64
+
65
+
66
+ # @router.post('/', status_code=status.HTTP_201_CREATED)
67
+ # def create_note(payload: schemas.NoteBaseSchema, db: Session = Depends(get_db)):
68
+ # new_note = models.Note(**payload.dict())
69
+ # db.add(new_note)
70
+ # db.commit()
71
+ # db.refresh(new_note)
72
+ # return {"status": "success", "note": new_note}
25
73
26
74
27
75
@router .patch ('/{noteId}' )
0 commit comments