API / app.py
Inayatgaming's picture
Update app.py
d7a5b08 verified
Raw History Blame Contribute Delete
1.9 kB
from fastapi import FastAPI, Query, HTTPException
from fastapi.responses import JSONResponse
import requests
import os
app = FastAPI(
title="API",
description="API",
version="1.0.0"
)
# Replace this with an API you own or are authorized to proxy.
API = os.getenv( "API" )
REQUEST_TIMEOUT = 20
@app.get("/")
def home():
return {
"status": True,
"message": "API is running"
}
@app.get("/api")
def lookup(
num: str = Query(..., min_length=1)
):
try:
response = requests.get(
API,
params={"num": num},
timeout=REQUEST_TIMEOUT,
headers={
"Accept": "application/json",
"User-Agent": "Mozilla/5.0"
}
)
response.raise_for_status()
result = response.json()
except requests.RequestException:
raise HTTPException(
status_code=502,
detail="Request failed"
)
except ValueError:
raise HTTPException(
status_code=502,
detail="Request failed"
)
# -----------------------------------------
# NO DATA RESPONSE
# -----------------------------------------
if result.get("success") is False:
return JSONResponse(
content={
"Main_Records": None,
"Alt_Records": None
}
)
# -----------------------------------------
# SUCCESS RESPONSE
# -----------------------------------------
data = result.get("data", {})
inner_data = data.get("Data", {})
return JSONResponse(
content={
"Main_Records": inner_data.get("Main_Records"),
"Alt_Records": inner_data.get("Alt_Records")
}
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
app,
host="0.0.0.0",
port=7860
)