Mr. Geologist
Mr. Geologist

Reputation: 75

How to feed a list of parameters to a function

I have a script I use to retrieve data from a Rest API, and a table of station values that I parse that I parse into two strings. The unique_id feeds into the api query while the name string is used to name the output csv:

import pandas as pd

station = "Stage.NAVD88@008474---5ca7816e01a34161b0e80c0ef8510cf5"


lst = param_string.split('---')
unique_id = lst[1]
name = lst[0]

print(name)
print(unique_id)
Stage.NAVD88@008474
5ca7816e01a34161b0e80c0ef8510cf

response = timeseries.get('/GetData', params=
                                   {'TimeSeriesUniqueIds': [unique_id])

df =pd.DataFrame(response)


path = r'C:\\'
outpath = path + name +  ".csv"
df.to_csv(outpath, index=False)

This works fine for single station strings, but if I have a list of strings that need to be parsed, I'm not sure how to feed them to the api query:

stations = ['Precip.Recorder@011285---84d22eef5b9640b0adfe9a6da61a54b1', 'Precip.Recorder@011288---dc23d83c3b34418a985543bf9133fab7']

I assume I'll need to loop through the list and split each string like:

for x in stations:
    print(x.split('---'))

['Precip.Recorder@011285', '84d22eef5b9640b0adfe9a6da61a54b1']
['Precip.Recorder@011288', 'dc23d83c3b34418a985543bf9133fab7']

but I'm not sure how to approach feeding each station name & id to the api query.

Upvotes: 0

Views: 64

Answers (1)

Ray
Ray

Reputation: 471

I'm unsure what the timeseries object refers to in your question, but I've replaced it with the requests library.

  • We first take your list of station values and make a Python dictionary of name and unique_id.
  • Then we loop through the dictionary, passing the unique_id to the API call and — if the response was successful — passing the name as the CSV filename.
from typing import Union

import pandas as pd
import requests


def main(stations: Union[str, list], url: str = "/GetData", path: str = r"C:\\") -> None:
    # Make request and CSV parameters map from provided station values
    params: dict = split_station_values(stations)
    # Send request and make CSV per station name and unique_id pair
    for name, unique_id in params.items():
        response = requests.get(url, params={"TimeSeriesUniqueIds": [unique_id]})
        if response.status_code == 200:
            outpath: str = f"{path}{name}.csv"
            df = pd.DataFrame(response.json())
            df.to_csv(outpath, index=False)


def split_station_values(stations: Union[str, list], delimiter: str = "---") -> dict:
    # Type cast if single station string
    if isinstance(stations, str):
        stations: list = [stations]
    # Make params mapping
    mapping: dict = {}
    for station in stations:
        name, unique_id = station.split(delimiter)
        mapping[name] = unique_id
    return mapping


if __name__ == "__main__":
    stations: list = ["Stage.NAVD88@008474---5ca7816e01a34161b0e80c0ef8510cf5",
                      "Precip.Recorder@011285---84d22eef5b9640b0adfe9a6da61a54b1",
                      "Precip.Recorder@011288---dc23d83c3b34418a985543bf9133fab7"]
    main(stations=stations)

Upvotes: 1

Related Questions