Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 166bf78

Browse files
author
Rafael
committed
Refactor crypto price retrieval and note creation logic in the API
1 parent ccc2da9 commit 166bf78

File tree

3 files changed

+55
-43
lines changed

3 files changed

+55
-43
lines changed

‎app/main.py

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ async def get_post(post_id: int):
4646
raise HTTPException(status_code=500, detail="Internal server error")
4747

4848

49-
@app.get('/crypto-price-ethereum2')
49+
@app.get('/crypto-price-ethereum')
5050
async def get_crypto_price():
5151
try:
5252
api_key = os.getenv("api_key")
@@ -67,39 +67,3 @@ async def get_crypto_price():
6767

6868
except Exception as e:
6969
raise HTTPException(status_code=500, detail=str(e))
70-
71-
@app.get('/crypto-price-ethereum')
72-
async def get_crypto_price():
73-
try:
74-
#Make a GET request to the API
75-
response = requests.get(f"https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&vs_currencies=usd&x_cg_demo_api_key=CG-2DiDAMj5CMnutZkqo3r1jxBJ")
76-
#Check if the request was successful (status code 200)
77-
if response.status_code == 200:
78-
return response.json()
79-
else:
80-
raise HTTPException(status_code=response.status_code, detail="API call failed")
81-
except Exception as e:
82-
raise HTTPException(status_code=500, detail="Internal server error")
83-
84-
85-
86-
87-
88-
# url = "https://api.coingecko.com/api/v3/simple/token_price/ethereum?contract_addresses=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&vs_currencies=usd&x_cg_demo_api_key=CG-2DiDAMj5CMnutZkqo3r1jxBJ"
89-
90-
# params = {
91-
# "contract_addresses": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
92-
# "vs_currencies": "usd",
93-
# "x_cg_demo_api_key": "CG-2DiDAMj5CMnutZkqo3r1jxBJ" # <- Move it here
94-
# }
95-
96-
# try:
97-
# response = requests.get(url, params=params, timeout=10) # <- No headers needed
98-
# response.raise_for_status()
99-
# data = response.json()
100-
# return JSONResponse(content={"status": "success", "data": data})
101-
# except requests.exceptions.RequestException as e:
102-
# raise HTTPException(
103-
# status_code=500,
104-
# detail=f"Error fetching crypto price: {str(e)}. URL: {url}"
105-
# )

‎app/note.py

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
from sqlalchemy.orm import Session
33
from fastapi import Depends, HTTPException, status, APIRouter, Response
44
from .database import get_db
5+
import requests
6+
import os
7+
from dotenv import load_dotenv
8+
9+
load_dotenv()
510

611
router = APIRouter()
712

@@ -14,14 +19,57 @@ def get_notes(db: Session = Depends(get_db), limit: int = 10, page: int = 1, sea
1419
models.Note.title.contains(search)).limit(limit).offset(skip).all()
1520
return {'status': 'success', 'results': len(notes), 'notes': notes}
1621

17-
1822
@router.post('/', status_code=status.HTTP_201_CREATED)
1923
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}
2573

2674

2775
@router.patch('/{noteId}')

‎output.PNG

15.6 KB
Loading[フレーム]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /