0

I am extracting data from this API I was able to save the JSON file on my local machine. I want to run the requests for several stocks. How do I do it? I tried to play with for loops but not good came out of this. I attached the code below. the out put is:

AAPL
[]
TSLA
[]

Thank you, Tal

try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import requests
import json
import time


def get_jsonparsed_data(url):
"""
Receive the content of ``url``, parse it as JSON and return the object.

Parameters
----------
url : str

Returns
-------
dict
"""
stock_symbol = ["AAPL","TSLA"]
for symbol in stock_symbol:
print (symbol)
#Sending the API request
r = requests.get('https://financialmodelingprep.com/api/v3/income-statement/symbol={stock_symbol}?limit=120&apikey={removed by me})
packages_JSON = r.json()
print(packages_JSON)
#Exporting the data into JSON file
with open('stocks_data321.json', 'w', encoding='utf-8') as f: 
    json.dump(packages_JSON, f, ensure_ascii=False, indent=4)
Tal_87_il
  • 29
  • 1
  • 7
  • Try copy the url in your get request, paste it in the browser and see if you get a response. If yes, instead of _r.json()_, do _r.text_ If you want async support to query multiple api at the same time, use [aiohttp](https://docs.aiohttp.org/en/stable). python3 only. – collinsuz Mar 12 '21 at 10:02
  • Does this answer your question? [Python requests with multithreading](https://stackoverflow.com/questions/38280094/python-requests-with-multithreading) – Stan Reduta Mar 12 '21 at 10:10

1 Answers1

1

Querying multiple APIs iterativelly will take a lot of time. Consider using theading or AsyncIO to do requests simultaniously and speed up the process.

In a nutshell you should do something like this for each API:

import threading

for provider in [...]:  # list of APIs to query
    t = threading.Thread(target=api_request_function, args=(provider, ...))
    t.start()

However better read this great article first to understand whats and whys of threading approach.

Stan Reduta
  • 3,292
  • 5
  • 31
  • 55