test_fastapi_get_web.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. from fastapi import FastAPI, HTTPException, Query
  2. import httpx
  3. import re
  4. app = FastAPI()
  5. @app.get("/")
  6. def read_root():
  7. return {"message": "FastAPI is running"}
  8. @app.get("/fetch-url/")
  9. async def fetch_url(url: str = Query(..., description="The URL to fetch")):
  10. async with httpx.AsyncClient() as client:
  11. try:
  12. response = await client.get(url)
  13. response.raise_for_status() # Check if the request was successful
  14. content = response.text
  15. price = '$' + re.findall('mainPrice__tM6aY"><p title="\$(.*?)"', content)[0]
  16. percentage = re.findall('"name\\":\\"Percent Change 24H\\",\"value\\":(.*?)},', content)[0] + '%'
  17. res = f"{price} {percentage}"
  18. return res
  19. except httpx.RequestError as e:
  20. raise HTTPException(status_code=400, detail=f"An error occurred while requesting {url}: {str(e)}")
  21. except httpx.HTTPStatusError as e:
  22. raise HTTPException(status_code=e.response.status_code,
  23. detail=f"Error response {e.response.status_code} while requesting {url}: {str(e)}")
  24. if __name__ == "__main__":
  25. import uvicorn
  26. uvicorn.run(app, host="0.0.0.0", port=34567)