Skip to content
Advertisement

how pass variables in api calll python?

i have a simple api call that should return me the news based on stock tickers i pass in the get request. But I would like to pass the data array to the API call. How do I pass all the values in the data list to the API call request?

def main():

    data = ["AAPL", "SQ", "PLTR"]
    // API call which I would like to pass values in data 
response = requests.get("https://stocknewsapi.com/api/v1tickers=data&items=50&date=last7days&token=myapikey")
  

Advertisement

Answer

You can use params in requests to use arguments in url

import requests

data = ["AAPL", "SQ", "PLTR"]
data_str = ",".join(data)

url = "https://stocknewsapi.com/api/v1"

payload = {
    "tickers": data_str,
    "items": 50,
    "date": "last7days",
    "token": "myapikey",
}

response = requests.get(url, params=payload)

Eventually you can use string formatting with {} and .format(data_str)

data_str = ",".join(data)

url = "https://stocknewsapi.com/api/v1?tickers={}&items=50&date=last7days&token=myapikey".format(data_str)

or f-string with {data_str}

data_str = ",".join(data)

url = f"https://stocknewsapi.com/api/v1?tickers={data_str}&items=50&date=last7days&token=myapikey"
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement