DEV Community

Nico Reyes
Nico Reyes

Posted on

API returned 401. My key was valid. Spent 3 hours finding out why.

API returned 401. My key was valid. Spent 3 hours finding out why.

Hit an API that kept rejecting my requests. Error said 401 Unauthorized. My API key was literally copied straight from their dashboard.

What broke

Building a script to pull data from a client analytics API. Got my API key, set it in the header, made the request.

Got back:

{
  "error": "Unauthorized",
  "message": "Invalid API key"
}
Enter fullscreen mode Exit fullscreen mode

Checked the key. Triple checked it. Copy pasted it again. Still 401.

Everything obvious didn't work

Googled the error. Stack Overflow said check your key format. I did. Looked fine.

Tried:

  • Regenerated the API key twice
  • Used curl instead of Python to rule out my code
  • Added the key as query parameter instead of header
  • Checked if my IP was maybe blocked

None of it worked. Getting frustrated at this point.

What actually fixed it

Read their docs again. Fourth time. Found this buried in the authentication reference section:

"API keys must be Base64 encoded before sending"

They give you a plaintext key in the dashboard. The API wants it Base64 encoded. Nowhere in the quickstart guide. Just one sentence buried in the auth docs.

Fixed it:

import requests
import base64

api_key = "your_plaintext_key_here"
encoded_key = base64.b64encode(api_key.encode()).decode()

headers = {
    "Authorization": f"Bearer {encoded_key}"
}

response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())
Enter fullscreen mode Exit fullscreen mode

Worked immediately.

Things that might help if you hit this

When stuck on API auth stuff:

  • Read the actual API reference docs, not just the quickstart
  • Check if they want some encoding (Base64, URL encoding, whatever)
  • Look for their example requests if they have any
  • Try their Postman collection if available

Still annoyed it took 3 hours for one line of code honestly.

Top comments (0)