Skip to content

GraphQL API

Nadia edited this page Jul 31, 2024 · 14 revisions

Python wrapper

As Jupyter Notebook

As a beginner's guide, we recommend exploring our tutorial (right click -> save link as... -> ensure the extension is .ipynb) designed as a Jupyter notebook for a swift introduction. Inside, you'll discover helpful wrappers and practical examples of GraphQL syntax. This notebook is prepped and ready for use, serving as both a useful wrapper on its own or a source from which you can copy Python functions to seamlessly integrate into your own scripts.

As Python script

You can use this minimal python script that doesn't require Jupyter environment. The example shows how to request total population inside the boundary provided as geojson.

import requests
import json

# The geometry in GeoJSON format to retrieve analytics
geojson = '{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "coordinates": [ [ [ 41.550028912224064, 41.68314163681433 ], [ 41.550028912224064, 41.55946643707131 ], [ 41.74542575095546, 41.55946643707131 ], [ 41.74542575095546, 41.68314163681433 ], [ 41.550028912224064, 41.68314163681433 ] ] ], "type": "Polygon" } } ] }'

# GraphQL query
query = """
{
  polygonStatistic ( polygonStatisticRequest: { polygon: %s })
  {
    analytics {
      functions(args:[
        {name:"sumX", id:"population", x:"population"},
      ]) { id, result }
    }
  }
}
"""

# Escape geojson string and substitute in GraphQL query string
query = query % json.dumps(geojson)

# Function to get OSM analytics from Insights API
def get_osm_analytics(query):
    # Insights API URL
    url = "https://apps.kontur.io/insights-api/graphql"
    # Payload is JSON with query field
    payload = { "query": query }
    response = requests.post(url, json=payload)
    return response.json()

analytics = get_osm_analytics(query)
print(json.dumps(analytics, indent=4))

API response:

{
    "data": {
        "polygonStatistic": {
            "analytics": {
                "functions": [
                    {
                        "id": "population",
                        "result": 205526.0
                    }
                ]
            }
        }
    }
}

Examples

Examples below can be copy-pasted to python script in place of query variable

Population statistics

Use this query to get statistical information about population, urban distribution, and economic indicators in a specified polygon:

{
  polygonStatistic (
    polygonStatisticRequest: {
      polygon: %s
    }
  )
  {
    analytics {
      population{population, urban, gdp}
    }
  }
}

The API response includes metrics related to population, urban distribution, and GDP:

{
    "data": {
        "polygonStatistic": {
            "analytics": {
                "population": {
                    "population": 203663.0,
                    "urban": 189771.0,
                    "gdp": 1201939763.0
                }
            }
        }
    }
}

Thermal spot statistics

Retrieve statistics on thermal spots, industrial area coverage, and forest area to monitor environmental conditions or assess the risk of natural disasters in a specified geographic area.

{
  polygonStatistic ( polygonStatisticRequest: { polygon: %s })
  {
    analytics {
      thermalSpotStatistic{industrialAreaKm2, hotspotDaysPerYearMax, volcanoesCount, forestAreaKm2}
    }
  }
}

API response:

{
    "data": {
        "polygonStatistic": {
            "analytics": {
                "thermalSpotStatistic": {
                    "industrialAreaKm2": 4.753741490005585,
                    "hotspotDaysPerYearMax": 2,
                    "volcanoesCount": 0,
                    "forestAreaKm2": 127.5480822241893
                }
            }
        }
    }
}

Urban core

Urban core highlights the most populated region (0-68% of entire polygon) - it's also can be explored in UI. Can be used for population density analysis or urban development planning.

This query provides boundaries of urban core and settled periphery in geojson format:

{
  polygonStatistic (polygonStatisticRequest: {polygon: %s})
  {
    analytics {
      humanitarianImpact
    }
  }
}

This query provides numbers for populated area vs urban core area:

{
  polygonStatistic ( polygonStatisticRequest: { polygon: %s })
  {
    analytics {
      urbanCore{urbanCorePopulation, urbanCoreAreaKm2, totalPopulatedAreaKm2}
    }
  }
}

API response:

{
    "data": {
        "polygonStatistic": {
            "analytics": {
                "urbanCore": {
                    "urbanCorePopulation": 138776.0,
                    "urbanCoreAreaKm2": 13.24,
                    "totalPopulatedAreaKm2": 147.1
                }
            }
        }
    }
}

Bunch of statistical functions

This example illustrates the various functions that our API can process. Feel free to modify the query to include only the functions that are essential for your needs. "name" is one of the functions, "x" is indicator, the "id" serves as a custom label that you define, and it is used to retrieve the corresponding result in the response.

{
  polygonStatistic (polygonStatisticRequest: {polygon: %s})
  {
    analytics {
      functions(args:[
        {name:"sumX", id:"population", x:"population"},
        {name:"sumX", id:"populatedAreaKm2", x:"populated_area_km2"},
        {name:"sumXWhereNoY", id:"areaWithoutOsmBuildingsKm2", x:"populated_area_km2", y:"building_count"},
        {name:"sumXWhereNoY", id:"areaWithoutOsmRoadsKm2", x:"populated_area_km2", y:"highway_length"},
        {name:"percentageXWhereNoY", id:"osmBuildingGapsPercentage", x:"populated_area_km2", y:"building_count"},
        {name:"percentageXWhereNoY", id:"osmRoadGapsPercentage", x:"populated_area_km2", y:"highway_length"},
        {name:"percentageXWhereNoY", id:"antiqueOsmBuildingsPercentage", x:"populated_area_km2", y:"building_count_6_months"},
        {name:"percentageXWhereNoY", id:"antiqueOsmRoadsPercentage", x:"populated_area_km2", y:"highway_length_6_months"},
        {name:"avgX", id:"averageEditTime", x:"avgmax_ts"},
        {name:"maxX", id:"lastEditTime", x:"avgmax_ts"},
        {name:"sumX", id:"osmBuildingsCount", x:"building_count"},
        {name:"sumX", id:"osmUsersCount", x:"osm_users"},
        {name:"sumX", id:"osmUsersHours", x:"total_hours"},
        {name:"sumX", id:"localOsmUsersHours", x:"local_hours"},
        {name:"sumX", id:"aiBuildingsCountEstimation", x:"total_building_count"}
      ]) {
        id,
        result
      }
    }
  }
}

Response includes:

  • population: The total population of the specified area.
  • populatedAreaKm2: The total populated area of the specified region
  • areaWithoutOsmBuildingsKm2: The area without OpenStreetMap (OSM) buildings, indicating gaps in building data.
  • areaWithoutOsmRoadsKm2: The area without OSM roads.
  • osmBuildingGapsPercentage: The percentage of gaps in OSM building data
  • osmRoadGapsPercentage: The percentage of gaps in OSM road data
  • antiqueOsmBuildingsPercentage: The percentage of antique OSM buildings that were added more than 6 months ago
  • antiqueOsmRoadsPercentage: The percentage of antique OSM roads that were added more than 6 months ago
  • averageEditTime: The average timestamp taken for edits in the OSM data.
  • lastEditTime: The timestamp of the last update in the OSM data.
  • osmBuildingsCount: The total count of buildings in the OSM data.
  • osmUsersCount: The total count of users contributing to the OSM data.
  • osmUsersHours: The total number of hours spent by all OSM users contributing to the data.
  • localOsmUsersHours: The total number of hours spent by local OSM contributors.
  • aiBuildingsCountEstimation: An estimated total building count in the area.
API response:
{
    "data": {
        "polygonStatistic": {
            "analytics": {
                "functions": [
                    {
                        "id": "population",
                        "result": 9503075.0
                    },
                    {
                        "id": "populatedAreaKm2",
                        "result": 74003.91374843268
                    },
                    {
                        "id": "areaWithoutOsmBuildingsKm2",
                        "result": 24995.907446610214
                    },
                    {
                        "id": "areaWithoutOsmRoadsKm2",
                        "result": 4984.313269719352
                    },
                    {
                        "id": "osmBuildingGapsPercentage",
                        "result": 33.776466919818276
                    },
                    {
                        "id": "osmRoadGapsPercentage",
                        "result": 6.735202257900738
                    },
                    {
                        "id": "antiqueOsmBuildingsPercentage",
                        "result": 86.68080292338021
                    },
                    {
                        "id": "antiqueOsmRoadsPercentage",
                        "result": 59.92741429341344
                    },
                    {
                        "id": "averageEditTime",
                        "result": 1632456632.2005708
                    },
                    {
                        "id": "lastEditTime",
                        "result": 1699595064.0
                    },
                    {
                        "id": "osmBuildingsCount",
                        "result": 2638693.0
                    },
                    {
                        "id": "osmUsersCount",
                        "result": 742544.0
                    },
                    {
                        "id": "osmUsersHours",
                        "result": 467415.0
                    },
                    {
                        "id": "localOsmUsersHours",
                        "result": 107505.0
                    },
                    {
                        "id": "aiBuildingsCountEstimation",
                        "result": 6874187.0
                    }
                ]
            }
        }
    }
}

Advanced analytics

{
  polygonStatistic (polygonStatisticRequest: {polygon: %s})
  {
    analytics {
        advancedAnalytics {
            numerator,
            denominator,
            numeratorLabel,
            denominatorLabel,
            resolution,
            analytics {
                value,
                calculation,
                quality
            }
        }
    }
  }
}

Indicators

The query returns the full list of available indicators that you can use with analytics functions

{
  polygonStatistic (polygonStatisticRequest: {polygon: %s})
  {
      bivariateStatistic{indicators{name, label, copyrights, direction}}
  }
}

It returns keys, names, copyrights and even sentiments - because they are used in Bivariate Matrix calculation.

API response (truncated):
{   
    "data": {
        "polygonStatistic": {
            "bivariateStatistic": {
                "indicators": [
                    {
                        "name": "count",
                        "label": "OSM: objects count",
                        "copyrights": [
                            "\u00a9 OpenStreetMap contributors https://www.openstreetmap.org/copyright"
                        ],
                        "direction": [
                            [
                                "bad"
                            ],
                            [
                                "good"
                            ]
                        ]
                    },
                    {
                        "name": "communications_capacity_index",
                        "label": "PDC GRVA Communications capacity index",
                        "copyrights": [
                            "\u00a9 2022 Pacific Disaster Center. https://www.pdc.org/privacy-policy/"
                        ],
                        "direction": [
                            [
                                "unimportant"
                            ],
                            [
                                "important",
                                "bad"
                            ]
                        ]
                    },
                    {
                        "name": "nurse_midwife_per_10k",
                        "label": "PDC NDPBA Nurse per 10000 persons",
                        "copyrights": [
                            "\u00a9 2022 Pacific Disaster Center. https://www.pdc.org/privacy-policy/"
                        ],
                        "direction": [
                            [
                                "important",
                                "bad"
                            ],
                            [
                                "unimportant",
                                "good"
                            ]
                        ]
                    },
...

Axis list

Used for MCDA drop-down layer list. Returns axis list (numerator/denominator pairs)

{
    getAxes {
        axis{
            label
            steps {
                label
                value
            }
            quality
            quotient
            quotients {
                name
                label
                emoji
                description
                copyrights
                direction
                unit {
                    id
                    shortName
                    longName
                }
            }
            transformation {
                transformation
                min
                mean
                stddev
                lowerBound
                upperBound
                skew
            }
            parent
        }
    }
}

Axis transformation details for MCDA

Returns 5 available transformations with graph points to visualize dataset distribution

{
    getTransformations(numerator: $numerator, denominator: $denominator) {
        transformation {
            transformation
            min
            mean
            stddev
            lowerBound
            upperBound
            skew
            points
        }
    }
}

Functions

Function

Description

sumX(x)

Calculates the sum of parameter X using data from all full hexes that the input geometry touches/overlaps.

avgX(x)

Calculates the average value of parameter X.

maxX(x)

Calculates the maximum value of parameter X.

minX(x)

Calculates the minimum value of parameter X.

countX(x)

Calculate the number of hexagons where parameter X is not null, using data from all full hexes that the input geometry touches/overlaps

sumXWhereNoY(x, y)

Calculates the sum of parameter X where parameter Y is absent using data from all full hexes that the input geometry touches/overlaps.

percentageXWhereNoY(x, y)

Calculates the percentage of sum X from the total sum where parameter Y is absent using data from all full hexes that the input geometry touches/overlaps.

Note: all hexes in the table are H3 hexes with resolution 8

Clone this wiki locally