Home > Back-end >  Efficiently using the OpenElevation API using Python
Efficiently using the OpenElevation API using Python

Time:07-09

I have a large set of latitude/longitude coordinates and would like to get the elevation for each. I want to use the OpenElevation API. According to their API Docs, I can get elevation data through the URL: https://api.open-elevation.com/api/v1/lookup?locations=10,10|20,20|41.161758,-8.583933. As you can see from the example URL, it is possible to get many elevations in a single request (provided you are using POST). However, when I try to implement the example they have used:


elevation = requests.post('https://api.open-elevation.com/api/v1/lookup', params={"locations": "10,10"}).content
print(elevation)

This is the result: b'{"error": "Invalid JSON."}'

The URL being submitted is: https://api.open-elevation.com/api/v1/lookup?locations=10,10 which is definitely in incorrect format.

CodePudding user response:

After taking a quick look at the documentation. The POST endpoint requires the parameters be sent in the request body in JSON format with the appropriate headers

Here is a working example:

import requests
import json

response = requests.post(
            url="https://api.open-elevation.com/api/v1/lookup",
            headers={
                "Accept": "application/json",
                "Content-Type": "application/json; charset=utf-8",
            },
            data=json.dumps({
                "locations": [
                    {
                        "longitude": 10,
                        "latitude": 10
                    },
                    {
                        "longitude": 20,
                        "latitude": 20
                    }
                ]
            })
        )

print('Response HTTP Status Code: {status_code}'.format(status_code=response.status_code))
print('Response HTTP Response Body: {content}'.format(content=response.content))

Response:

Response HTTP Status Code: 200
Response HTTP Response Body: b'{"results": [{"latitude": 10, "longitude": 10, "elevation": 515}, {"latitude": 20, "longitude": 20, "elevation": 545}]}'
  • Related