I am getting "Failed to fetch data for symbol AAPL. Status code: 403" response from the following code:
@app.route('/get_recommendations', methods=['GET', 'POST'])
def get_recommendations(symbol):
url = f"https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}?modules=recommendationTrend&corsDomain=finance.yahoo.com&formatted=false"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return data
else:
print(f"Failed to fetch data for symbol {symbol}. Status code: {response.status_code}")
return None
I am expecting to get recommendations for stock symbol from yfinance.
HTTP 403 means you aren't authorized to make requests against the given endpoint. This is happening because the Yahoo Finance API was shut down in 2017. The only way to do it now is via screen scraping, which is almost always a bad idea. That being said, there's an existing library for this: yfinance
While I'm here, here's a slight refactor of your code that makes better use of Requests and doesn't print (which is a bad practice).