jsonpowershellcsvdarksky

How to design an "Invoke-WebRequest" for multiple API calls with more than one variable from CSV?


I am trying to call Dark Sky API for weather forecast data for each location in a CSV file with hundreds lines and write them to a text file. Here's an example of the first 5 lines of the CSV...

ip              city        region_code zip     latitude  longitude
75.161.17.209   Albuquerque NM          87114   35.1868  -106.6652
68.55.28.227    Plymouth    MI          48170   42.3688  -83.4799
72.95.198.227   Homestead   PA          15120   40.3926  -79.9052
68.180.94.219   Normal      IL          61761   40.5124  -88.9883
75.132.165.245  Belleville  IL          62226   38.5352  -90.0006

The uri is formatted like this...

https://api.darksky.net/forecast/[APIKey]/$latitude ,$longitude ,$ForcastTime ?exclude=currently,minutely,hourly,flags&units=us

There are 3 variables in this uri. $latitude, $longitude, and $ForecastTime. $ForecastTime is easy, because it is the same for all requests, so I have that defined already as...

$ForecastTime = Get-Date -Date $(Get-Date).AddDays(1) -Format yyyy-MM-ddTHH:mm:ss

...in order to give me Tomorrow's forecast info. This is the format Dark Sky calls for and works just fine.

I'm having trouble defining $latitude and $longitude as variables and formatting the Invoke-WebRequest so I can pull the weather data for the entire string of locations.

Any help would be appreciated.


Solution

  • Here is some sample code with Invoke-RestMethod but you can also work with Invoke-WebRequest. I like using Invoke-RestMethod for interacting with APIs.. Try and let me know if it works or not.

    $ForecastTime = Get-Date -Date $(Get-Date).AddDays(1) -Format yyyy-MM-ddTHH:mm:ss;
    Import-CSV './input.csv' | ForEach-Object {
         $result = Invoke-RestMethod -Uri "https://api.darksky.net/forecast/$apiKey/$_.latitude,$_.longitude,$ForcastTime?exclude=currently,minutely,hourly,flags&units=us"
    }
    

    PS: If a CSV column name has spaces in it then you can read the column as $_.'Region Code'