{'message': 'forbidden.'} What am I doing wrong?

import requests
import json

endpoint = "https://data.sandbox.alpaca.markets/v2"
headers = json.loads(open("key.txt",'r').read())

symbol = "MSFT"
bar_url = endpoint + "/stocks/{}/bars".format(symbol)
params = {"start" : "2022-01-01",
          "limit" : 600,
          "timeframe" : "1Hour"}

r = requests.get(bar_url, headers = headers, params = params)

data = r.json()

I have also tried this with url

https://data.alpaca.markets/v2

Additionally I have regenerated my key several times and made sure the correct key was brought over.

Every time I get the error: {‘message’: ‘forbidden.’}
Can someone please tell me what im doing wrong here?

You have to provide the secret id/key in HTTP request headers. Read more information here. This info is placed into the Trading API section of the new documentation but the authentication process is the same for all REST APIs provided by Alpaca.

Hi Oleg, isn’t that what im doing? the key.txt file contains json with my key and ID which are assigned to the headers variable. If this is incorrect, can you show me in code how to fix this issue? I am new to alpacas api.

Thank you

key.txt

{
"APCA_API_KEY_ID" : "XXXXXXXXXXXXX",
"APCA_API_SECRET_KEY" : "XXXXXXXXXXXXXXXXXXXXXXX"
}

I’m not a Python developer. Your code looks fine but I’m not sure how headers passed into the requests.get function. Why not just check how it works with the official Python SDK?

So looked at it appears according to this it’s just expecting a dictionary
https://docs.python-requests.org/en/master/user/quickstart/

I updated my code to directly pass the key values to the headers parameter and im still getting the same error

import requests
import json

endpoint = "https://data.alpaca.markets/v2"
headers = json.loads(open("key.txt",'r').read())

symbol = "MSFT"
bar_url = endpoint + "/stocks/{}/bars".format(symbol)
params = {"start" : "2022-01-01",
          "limit" : 600,
          "timeframe" : "1Hour"}

r = requests.get(bar_url, headers = {'APCA_API_KEY_ID':'XXXXXXXX','APCA_API_SECRET_KEY':'XXXXXXXXX'}, params = params)

data = r.json()

How confident are you that it’s the headers?

You should use dashes instead of underscores in header names. Read the documentation carefully.

1 Like

I can’t believe it that worked. Thank you!