How to loop through list during API call? - python

I am looking to loop through about 5 stock tickers using an API. Currently I have "MSFT" as the only stock being called; however, I would like to make a stock list to return multiple responses.
For example:
stock_list = ["MSFT", "AAPL", "LMD", "TSLA", "FLGT"]
How can I request all 5 of these stocks to the querystring to print each response? Here is what I have currently which prints only "MSFT" into a json format...
import requests
#Use RapidAPI request to call info on Stocks
url = "https://alpha-vantage.p.rapidapi.com/query"
querystring = {"function":"GLOBAL_QUOTE","symbol": "MSFT"}
headers = {
'x-rapidapi-key': "KEY INSERTED HERE,
'x-rapidapi-host': "alpha-vantage.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)

Try using a for loop.
import requests
url = 'https://alpha-vantage.p.rapidapi.com/query'
headers = {
'x-rapidapi-key': '<API KEY>',
'x-rapidapi-host': 'alpha-vantage.p.rapidapi.com',
}
tickers = ['MSFT', 'AAPL', 'LMD', 'TSLA', 'FLGT']
for ticker in tickers:
querystring = {'function': 'GLOBAL_QUOTE', 'symbol': ticker}
r = requests.get(url, headers=headers, params=querystring)
print(r.json())
You can also try pretty printing the json output using the json module.
import json
# ... your code ...
for ticker in tickers:
# ... your code ...
print(json.dumps(r.json(), indent=2))
Also, you should delete your API key before its abused by anyone! These have to be kept safe somewhere.

Related

python dynamic value in api payload

Hey i have an api request and i need the value in payload to by dynamic, i tried with f'' but it wont make it dynamic
will appreciate your help.
import requests
url = "https://www.stie.com/api/conversations/KJQ-CZHNR-985/fields"
valuetarget = "123"
payload = {'apikey': 'zbyc88srdi333d3dpq5lye48pgg1tfo1pnjvj65ld',
'customfields': '[{"code": "orderno", "value":"valuetarget"}]'}
files = [
]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
You just need to load json and dump it to string and send it.
import json
valuetarget = "123"
payload = {
'apikey': 'zbyc88srdi333d3dpq5lye48pgg1tfo1pnjvj65ld',
'customfields':
json.dumps([{"code": "orderno", "value":valuetarget}])
}
You should escape the curly braces in the formatted string, like so:
f'[{{"code": "orderno", "value":"{valuetarget}"}}]'
But why not let requests format the string for you?
import requests
url = "https://www.stie.com/api/conversations/KJQ-CZHNR-985/fields"
valuetarget = "123"
# 'customfields' is now a list of dictionaries
payload = {'apikey': 'zbyc88srdi333d3dpq5lye48pgg1tfo1pnjvj65ld',
'customfields': [{"code": "orderno", "value": valuetarget}]}
files = [
]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)

Hubspot API Not Populating Deal

When I'm trying to create a deal through the hubspot api, all that is being created is a completely blank deal even though I am passing through populated data
Api Url: https://developers.hubspot.com/docs/api/crm/deals
Here is the following code that I am trying:
import json
import requests
hubspot_api_key = "MY_API_KEY"
url = 'https://api.hubapi.com/crm/v3/objects/deals?hapikey={}'.format(hubspot_api_key)
headers = {"Content-Type": "application/json"}
deals_post = {
'amount': "4034.75",
'closedate': '2021-05-10T12:04:00.000Z',
'dealname': 'Custom data integrations',
'dealstage': 'closedwon',
'hubspot_owner_id': "5448459615",
'pipeline': 'default'
}
response = requests.post(url, headers=headers, data=json.dumps(deals_post))
print(response.text)
And here is the result of it:
The solution to this issue would be adding properties to the data dictionary
import json
import requests
hubspot_api_key = "MY_API_KEY"
url = 'https://api.hubapi.com/crm/v3/objects/deals?hapikey={}'.format(hubspot_api_key)
headers = {"Content-Type": "application/json"}
deals_post = {
'properties': {
'amount': "4034.75",
'closedate': '2021-05-10T12:04:00.000Z',
'dealname': 'Custom data integrations',
'dealstage': 'closedwon',
'hubspot_owner_id': 83849850,
'pipeline': 'default'
}
}
response = requests.post(url, headers=headers, data=json.dumps(deals_post))
print(response.text)
This results in a filled out deal according to the data that was passed in

Yahoo Finance API not showing real time quote price

I am trying to get a stock price response however I am getting different results. Here is my attempt
import requests
url = "https://yahoo-finance-low-latency.p.rapidapi.com/v6/finance/quote"
querystring = {"symbols":"AAPL"}
headers = {
'x-rapidapi-key': "xxx",
'x-rapidapi-host': "yahoo-finance-low-latency.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
Here is the Documentation. Basically, the script is the same as the template yet it is not showing minute-by-minute price data. I am expecting a response similar to this one ...
I think you want to use the chart API:
url = "https://yahoo-finance-low-latency.p.rapidapi.com/v8/finance/chart/AAPL"
querystring = {"interval":"1m"}
headers = {
'x-rapidapi-key': "XXX",
'x-rapidapi-host': "yahoo-finance-low-latency.p.rapidapi.com"
}
api_result = requests.request("GET", url, headers=headers, params=querystring)
api_response = api_result.json()
print(api_response)

Pagination SendinBlue Api Call

I'm been trying to get data from the SendinBlue API. The problem is the API have a limit of 100 registers per call and my Python loop is not working properly. This is what I have so far, the call works fine.
import requests
import pandas as pd
from pandas import json_normalize
import json
results = []
pagination = 0
url = "https://api.sendinblue.com/v3/smtp/statistics/events"
querystring = {"limit":"100","offset":pagination,"days":"15"}
headers = {
"Accept": "application/json",
"api-key": "XXXXXXX"
}
#respuesta de la API
response = requests.request("GET", url, headers=headers, params=querystring)
#convertir json a diccionario
data = json.loads(response.text)
#convertir diccionario a DataFrame
base = pd.json_normalize(data,record_path='events')
The data structure is like this:
{'events': [
{'email': 'chusperu#gmail.com',
'date': '2020-10-18T17:18:58.000-05:00',
'subject': 'Diego, ¡Gracias por registrarte! đŸ˜‰',
'messageId': '<202010181429.12179607081#smtp-relay.mailin.fr>',
'event': 'opened',
'tag': '',
'from': 'ventas01#grupodymperu.com',
{'email': 'cynthiaapurimac#gmail.com',
'date': '2020-10-18T17:52:56.000-05:00',
'subject': 'Alvarado, ¡Gracias por registrarte! đŸ˜‰',
'messageId': '<202010182252.53640747487#smtp-relay.mailin.fr>',
'event': 'requests',
'tag': '',
'from': 'ventas01#grupodymperu.com'},
....
The loop I have tried is this, but it only paginated the first 200 registers. What I'm doing wrong?
for i in data['events']:
results.append(i)
while response.status_code == 200:
pagination += 100
querystring ['offset'] = pagination
response = requests.request("GET", url, headers=headers, params=querystring)
data = json.loads(response.text)
for i in data['events']:
results.append(i)
else:
break
print(results)
Finally get it.
import requests
import pandas as pd
from pandas import json_normalize
import json
# Excel = "C:/Users/User/PycharmProjects/Primero/DataSendin.xlsx"
pagination = 0
url = "https://api.sendinblue.com/v3/smtp/statistics/events"
querystring = {"limit":"100","offset":f"{pagination}","days":"3"}
headers = {
"Accept": "application/json",
"api-key": "Your API key"
}
response = requests.request("GET", url, headers=headers, params=querystring)
#respuesta de la API
try:
#convertir json a diccionario
results = []
data = json.loads(response.text)
results.append(data)
if not data:
print("no hay data")
else:
while response.status_code == 200:
pagination += 100
querystring ['offset'] = pagination
response = requests.request("GET", url, headers=headers, params=querystring)
data = json.loads(response.text)
results.append(data)
if not data:
break
except ValueError:
"no data"
#convertir diccionario a DataFrame
final = list(filter(None, results))
base = pd.json_normalize(final,record_path='events')
base

Looping through an array of API values for API GET request in Python

I have an array of ice cream flavors I want to iterate over for an API GET request. How do I loop through an array such as [vanilla, chocolate, strawberry] using the standard API request below?
import requests
url = "https://fakeurl.com/values/icecreamflavor/chocolate?"
payload = {}
headers = {
'Authorization': 'Bearer (STRING)',
'(STRING)': '(STRING)'
}
response = requests.request("GET", url, headers=headers, data = payload)
my_list = (response.text.encode('utf8'))
You could probably try string formatting on your url. You could loop through your array of ice-cream flavors, change the url in each loop and perform API GET request on the changed url.
import requests
iceCreamFlavors = ["vanilla", "chocolate", "strawberry"]
url = "https://fakeurl.com/values/icecreamflavor/{flavor}?"
payload = {}
headers = {
'Authorization': 'Bearer (STRING)',
'(STRING)': '(STRING)'
}
my_list = []
for flavor in iceCreamFlavors:
response = requests.request("GET", url.format(flavor=flavor), headers=headers, data = payload)
my_list.append(response.text.encode('utf8'))

Categories

Resources