The below FastAPI application is supposed to send a Bearer token over to an external api, but I keep on getting 401 unauthorized. My first suspicion was that the actual token retrieved from the /token endpoint was coming empty or malformed, but it is not.
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.get('/query')
async def getToken():
async with httpx.AsyncClient(verify=False) as client:
response = await client.get('https://myTokenApi.com/token')
access_token = response.json().get("access_token")
print(response.text)
try:
email = "myEmail@provider.com"
response_api = await client.get(f"https://externalApi.com/email/{email}", headers={"Content-Type":"application/json", "Authorization": f"Bearer {access_token}"})
print(response_api.status_code, response_api.text)
print(response_api.raise_for_status())
except httpx.HTTPStatusError as e:
print(e)
return response_api.json()
if __name__ == '__main__':
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=3000, log_level="info", reload=True)
I can properly test it with insomnia or postman and both api's are responding just fine. I have also tried grabbing just access_token from the json being returned, to make sure i'm sending the right piece, but I still have an error:
An exception is raised saying this is not a valid JSON, but printing out all the stuff, it looks valid:
returned JSON {'access_token': 'xxxxxxxxxxxxxxxxxxxxxxSomething', 'expires_in': 3600, 'token_type': 'Bearer'}
The mentioned exception is
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The problem was at the header content. So, instead of
headers={"Content-Type":"application/json", "Authorization": f"Bearer {access_token}"
I moved the headers from the httpx "client" declaration to outside and replaced it by this:
headers={"Accept":"*/*", "Token": f"Bearer {access_token}"
i only figured this out when I was looking at the token endpoint curl request being genarated at the token app swagger. That was the reason behind the 401 response and utimately the json error