Input CSV file of lat and long coordinates into API to extract the weather data?

867 views Asked by At

Here is my code below where I used long and lat coordinates in locations variable and attached it to the URL via coordinates_str. SInce I have CSV file which has latitude and longitude coordinates of around many locations and then call that CSV file as a input to this API(that needs authentication). How do I input CSV file into this code instead of locations variable?

import requests
import pprint

locations = [(13.84, -12.57), (12.21, -14.69)]

coordinates_str = ','.join(map(lambda a: ' '.join(f'{f:.3f}' for f in a), locations))

# Replace "poi-settings" with the endpoint you would like to call.

URL = f'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates={coordinates_str}'
TOKEN = 'TOKEN KEY'

# Create session object that can be used for all requests.
session = requests.Session()
session.headers['Authorization'] = 'Token {token}'.format(token=TOKEN)

# Send GET request to UBIconnect.
res = session.get(URL)
res.raise_for_status()

# Decode JSON response.
poi_info = res.json()
pprint.pprint(poi_info, indent=2, compact=True)

Then I tried this way: in place of coordinates_str I did this

import requests
import pprint
import pandas as pd 

df = pd.read_csv(r'E:\route_points.csv')
print(df)


# Replace "poi-settings" with the endpoint you would like to call.
URL = f'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?'
TOKEN = 'API TOKEN'
params= {'coordinates':(df)}

# Create session object that can be used for all requests.
session = requests.Session()
session.headers['Authorization'] = 'Token {token}'.format(token=TOKEN)

# Send GET request to UBIconnect.
res = session.get(URL, params= params)
res.raise_for_status()

# Decode JSON response.
poi_info = res.json()
pprint.pprint(poi_info, indent=2, compact=True)

Still not working.

Format needed to call the API from Documentation is:

# Replace "poi-settings" with the endpoint you would like to call.
URL = 'https://ubiconnect-eu.ubimet.com:8090/poi-settings'
TOKEN = '<YOUR TOKEN GOES HERE>'

so I replaced the poi-settings by pinpoint-data

URL = 'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates=longitude<space<latitude'

For Example: I put one coordinate set into API URL

URL = 'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates=132.85 12.84'

then with above URL I get the weather data for that location.

2

There are 2 answers

9
Martin Evans On BEST ANSWER

If you just want to submit a block of coordinates at a time from your CSV file then something like the following should suffice:

from itertools import islice
import requests
import pprint
import csv

def grouper(n, iterable):
    it = iter(iterable)
    return iter(lambda: tuple(islice(it, n)), ())


block_size = 10   # how many pairs to submit per request
TOKEN = 'TOKEN KEY'

# Create session object that can be used for all requests.
session = requests.Session()
session.headers['Authorization'] = 'Token {token}'.format(token=TOKEN)

with open('coordinates.csv', newline='') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)        # skip the header
    
    for coords in grouper(block_size, csv_input):
        coordinates = ','.join(f'{float(long):.3f} {float(lat):.3f}' for long, lat in coords)
        print(coordinates)
        
        URL = f'https://ubiconnect-eu.ubimet.com:8090/pinpoint-data?coordinates={coordinates}'

        # Send GET request to UBIconnect.
        res = session.get(URL)
        res.raise_for_status()
        
        # Decode JSON response.
        poi_info = res.json()
        
        pprint.pprint(poi_info, indent=2, compact=True)

(obviously this was not tested - no token). Make sure there are no blank lines in your CSV file.


To output to a file add an output file:

with open('coordinates.csv', newline='') as f_input, open('output.json', 'w', encoding='utf-8')  as f_output:

and use this in the pprint() call:

pprint.pprint(poi_info, f_output, indent=2, compact=True)
f_output.write('\n')    # add blank line if needed
9
Akash On

Hope this is what you are looking for

import csv
locations = list()
with open("foo.csv") as csvf:
    csvreader = csv.DictReader(csvf)    
    for row in csvreader:
        locations.append((float(row["lat"]), float(row["long"])))
# now add your code
coordinates_str = ','.join(map(lambda a: ' '.join(f'{f:.3f}' for f in a), locations))