Invalid Authorization Header

Hello. I am not good with using APIs and HTTP requests.
Company asked to scraped data from Companies House.
I am making some test requests in Python, but I get

{"error":"Invalid Authorization header","type":"ch:service"}

My code is:

payload={}
headers = {'Authorization': 'API my_api_key'}
url_cust = "https://api.company-information.service.gov.uk/company/01234567/"
rep = requests.request("GET", url_cust, headers=headers, data=payload, verify=False)

Can anyone help me out with this? I think the problem is either with my request, or with the way I generated my API key(no restricted IPs specified, no JavaScript domains)

The problem is with your authorisation header. Try this:

import base64
encoded_credentials = base64.b64encode('api_key:'.encode("utf-8")).decode("utf-8")
headers = {'Authorization': f"Basic {encoded_credentials}"}

The header should be the word Basic followed by a space, followed by the base64 encoding of api_key: (note the colon after your api key!).

Thank you very much for your reply. I tried this, but now I have this error:

{"error":"Invalid Authorization","type":"ch:service"}

Basically the same, but now just Invalid Authorization. Now I may assume this is the problem of me generating API keys incorrectly.

Update:

I found a solution to the “Invalid Authorization” problem on the following post:
Postman API call - API Issues - Companies House Developer Forum (chdev.org)

I changed Application environment from Test to Live.

If you are new to CompaniesHouseAPI it’s always best to set up your POSTMAN first, make a few requests and understand how the Authorization headers work. Once that is taken care of - putting that in code becomes a lot easier. Do note you will need OAuth 2 for certain use cases → Authentication

1 Like

Dear @azamat.ilyassov ,

firstly you need to generate an API_Key at your Developer Hub account(How to regenerate an API Key - #3 by MArkWilliams).
Then the request in Python is straightforward:
r = requests.get(url, auth=(API_Key , “”))

where API_Key is the generated API_Key by which the server authenticates you.