NAV Navbar
cURL

Introduction

Welcome to the Resource Watch API Documentation.

Authentication

The RW API uses JWT (JSON Web Tokens) to identify and authenticate its users. This token must be provided inside an Authorization header, with the form Bearer: <token>.

However, in order to perform GET requests for content that is not private, there’s no need for any sort of authentication or token.

How to generate your private token

To generate your own token, perform the following steps:

  1. Navigate to here. If you aren’t logged in yet, the application will redirect you to the login page. You will see the login page:

Control Tower login page

You can login with your WRI credentials (email and password) or with other auth providers (a Google, Facebook, or Twitter account). If you can’t remember your password (don’t worry! it happens to everyone!) you can reset your password clicking on ‘Recover password’.

  1. After logging in you will be redirected to the Control Tower application and you will see its front page: Control Tower Dashboard

  2. To obtain your token, click in the Profile menu item and you will see the token: Control Tower Profile

  3. Copy your token clicking the Copy button. Remember to add the header Authorization: Bearer: <yourToken> to any API call to authenticate yourself.

How to create a new user

To create a new user make a request like the one in the sidebar:

curl -X POST https://api.resourcewatch.org/auth/user \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
    "email":"<email>",
    "role":"<role>",
    "extraUserData": {
      "apps": [
        "<apps>"
      ]
    }
}'

There are three allowed roles: USER, MANAGER and ADMIN. The 'apps’ field only permits applications that are powered by the API: rw, gfw, prep, etc.

Dataset

What is a Dataset?

A dataset abstracts the data that can be obtained from several sources into a common interface. There are several data providers supported in the API, and each of those has a different provider. Datasets can belong to several applications.

Supported dataset sources

Third party Dataset connectors

For data stored on third party services.

Carto

(connectorType: 'rest', provider: 'cartodb')
Carto CARTO is an open, powerful, and intuitive map platform for discovering and predicting the key insights underlying the location data in our world.

ArcGIS Feature service

(connectorType: 'rest', provider: 'featureservice') Logo esri
ArcGIS for server is a Complete, Cloud-Based Mapping Platform.

Google Earth Engine

(connectorType: 'rest', provider: 'gee') Googleearthengine grey 108
Google Earth Engine combines a multi-petabyte catalog of satellite imagery and geospatial datasets with planetary-scale analysis capabilities and makes it available for scientists, researchers, and developers to detect changes, map trends, and quantify differences on the Earth’s surface.

Web Map Services (WMS)

(connectorType: 'wms', provider: 'wms')

WMS connector provides access to data served through OGC WMS protocol standard.

Rasdaman (Raster Data Manager)

(connectorType: 'rest', provider: 'rasdaman')
Rasdaman is a database with capabilities for storage, manipulation and retrieval of multidimensional arrays.

Internal storage connectors

For data stored in our system.

NEX-GDDP

(connectorType: 'rest', provider: 'nexgddp')
The NASA Earth Exchange Global Daily Downscaled Projections (NEX-GDDP) dataset is comprised of downscaled climate scenarios for the globe that are derived from the General Circulation Model (GCM) runs conducted under the Coupled Model Intercomparison Project Phase 5 (CMIP5) and across two of the four greenhouse gas emissions scenarios known as Representative Concentration Pathways (RCPs).

Comma-Separated Values (CSV)

(connectorType: 'document', provider: 'csv')
Arbitrary Comma-Separated Values data

Tab-Separated Values (TSV)

(connectorType: 'document', provider: 'tsv')
Arbitrary tab-Separated Values data

JavaScript Object Notation (JSON)

(connectorType: 'document', provider: 'json')
Arbitrary json structured data

XML

(connectorType: 'document', provider: 'xml')
Arbitrary XML data documents

Getting all datasets

This endpoint will allow to get all datasets available in the API:

curl -X GET https://api.resourcewatch.org/v1/dataset

Response:

{
    "data": [
        {
        "id": "00f2be42-1ee8-4069-a55a-16a988f2b7a0",
        "type": "dataset",
        "attributes": {
            "name": "Glad points",
            "slug": "Glad-points-1490086842129",
            "type": null,
            "subtitle": null,
            "application": ["data4sdgs"],
            "dataPath": null,
            "attributesPath": null,
            "connectorType": "document",
            "provider": "csv",
            "userId": "58333dcfd9f39b189ca44c75",
            "connectorUrl": "http://gfw2-data.s3.amazonaws.com/alerts-tsv/glad_headers.csv",
            "tableName": "data",
            "status": "pending",
            "published": true,
            "overwrite": false,
            "verified": false,
            "blockchain": {},
            "env": "production",
            "geoInfo": false,
            "legend": {
                "date": [],
                "region": [],
                "country": []
                },
            "clonedHost": {},
            "errorMessage": null,
            "updatedAt": "2017-01-13T10:45:46.368Z",
            "widgetRelevantProps": [],
            "layerRelevantProps": []
            }
        },
    ...
  ],
  "links": {
    "self": "http://api.resourcewatch.org/v1/dataset?page[number]=1&page[size]=10",
    "first": "http://api.resourcewatch.org/v1/dataset?page[number]=1&page[size]=10",
    "last": "http://api.resourcewatch.org/v1/dataset?page[number]=99&page[size]=10",
    "prev": "http://api.resourcewatch.org/v1/dataset?page[number]=1&page[size]=10",
    "next": "http://api.resourcewatch.org/v1/dataset?page[number]=2&page[size]=10"
  },
  "meta": {
    "total-pages": 99,
    "total-items": 990,
    "size": 10
  }
}

Slug & dataset-id

Datasets have an auto-generated and unique slug and id that allows the user to get, create, update, query or clone that dataset.

The dataset slug and the id cannot be updated even if the name changes.

Error Message

When a dataset is created the status is set to “pending” by default. Once the adapter validates the dataset, the status is changed to “saved”. If the validation fails, the status will be set to “failed” and the adapter will also set an error message indicating the reason.

Filters

The dataset list provided by the endpoint can be filtered with the following attributes:

Filter Description Accepted values
name Allow us to filter by name any valid text
type Allow us to distinguish between tabular and raster datasets raster or tabular
app Aplications to which this dataset is being used Available Aplications like: ["data4sdgs","gfw","rw","aqueduct","prep","forest-atlas","gfw-climate","aqueduct-water-risk","test","gfw-pro","globalforestwatch", "ghg-gdp"]
connectorType rest or document
provider Dataset provider this include inner connectors and 3rd party ones A valid dataset provider
userId the user who registered the dataset valid id
status the internal dataset status at connection time pending, saved or failed
published trueor false
env If the dataset is in preproduction envirenment or in production one productionor preproduction
overwritted If the data can be overwritten (only for being able to make dataset updates) trueor false
verify If this dataset contains data that is verified using blockchain trueor false
protected If it’s a protected layer trueor false
geoInfo If it contains intersectable geographical info trueor false

Filtering datasets

curl -X GET https://api.resourcewatch.org/v1/dataset?name=birds&provider=cartodb

For inclusive filtering with array props use ’@’

curl -X GET https://api.resourcewatch.org/v1/dataset?app=gfw@rw@prep

Sorting

Basics of sorting

The API currently supports sorting by means of the sort parameter.

Sorting datasets

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=name

Multiple sorting criteria can be used, separating them by commas.

Sorting datasets by multiple criteria

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=name,description

You can specify the sorting order by prepending the criteria with either - or +. By default, asc order is assumed.

Explicit order of sorting

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=-name,+description

Special sorting criteria

There are four special sorting criteria:

Special search criteria must be used as sole sorting criteria, as it’s not possible to combine any of them with any other search criteria.

Sorting datasets with special criteria

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=-most-favourited
curl -X GET https://api.resourcewatch.org/v1/dataset?sort=relevance&status=saved&search=agriculture

Relationships

Available relationships: Any dataset relationship [‘widget’, 'layer’, 'vocabulary’, 'metadata’]

Including relationships

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=slug,-provider,userId&status=saved&includes=metadata,vocabulary,widget,layer

Advanced filters

By vocabulary-tag matching

Matching vocabulary tags

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=slug,-provider,userId&status=saved&includes=metadata,vocabulary,widget,layer&vocabulary[legacy]=umd

Pagination

Field Description Type
page[size] The number elements per page Number
page[number] The page number Number

Paginating the output

curl -X GET https://api.resourcewatch.org/v1/dataset?sort=slug,-provider,userId&status=saved&includes=metadata,vocabulary,widget,layer&vocabulary[legacy]=threshold&page[number]=1
curl -X GET https://api.resourcewatch.org/v1/dataset?sort=slug,-provider,userId&status=saved&includes=metadata,vocabulary,widget,layer&vocabulary[legacy]=threshold&page[number]=2

How to get a specific dataset

To get a dataset:

curl -X GET https://api.resourcewatch.org/v1/dataset/51943691-eebc-4cb4-bdfb-057ad4fc2145

Response:

{
    "data": {
        "id": "51943691-eebc-4cb4-bdfb-057ad4fc2145",
        "type": "dataset",
        "attributes": {
            "name": "Timber Production RDC (test)",
            "slug": "Timber-Production-RDC-test-1490086842132",
            "type": null,
            "subtitle": null,
            "application": ["forest-atlas"],
            "dataPath": null,
            "attributesPath": null,
            "connectorType": "document",
            "provider": "csv",
            "userId": "58750a56dfc643722bdd02ab",
            "connectorUrl": "http://wri-forest-atlas.s3.amazonaws.com/COD/temp/annual%20timber%20production%20DRC%20%28test%29%20-%20Sheet1.csv",
            "tableName": "index_51943691eebc4cb4bdfb057ad4fc2145",
            "status": "saved",
            "overwrite": false,
            "legend": {
                "date": ["year"],
                "region": [],
                "country": [],
                "long": "",
                "lat": ""
            },
            "clonedHost": {},
            "errorMessage": null,
            "createdAt": "2017-01-25T21:48:27.535Z",
            "updatedAt": "2017-01-25T21:48:28.675Z"
        }
    }
}

To get the dataset including its relationships:

curl -X GET https://api.resourcewatch.org/v1/dataset/06c44f9a-aae7-401e-874c-de13b7764959?includes=metadata,vocabulary,widget,layer

Creating a Dataset

To create a dataset, you will need an authorization token. Follow the steps of this guide to get yours.

To create a dataset, you need to define all of the required fields in the request body. The fields that compose a dataset are:

Field Description Type Values Required
name Dataset name Text Any Text Yes
type Dataset type Text Any Text No
subtitle Dataset subtitle Text Any Text No
application Applications the dataset belongs to Array Any valid application name(s) Yes
connectorType Connector type Text rest, document, wms Yes
provider The connectorType provider Text cartodb, feature service, gee, csv, tsv, xml, json, nexgddp Yes
connectorUrl Url of the data source Url Any url Yes (except for gee, nexgddp and json formats)
tableName Table name Text Any valid table name No (just for GEE and nexgddp datasets)
data JSON DATA only for json connector if connectorUrl not present JSON [{},{},{}] No (just for json if connectorUrl is not present)
dataPath Path to the data in a json dataset Text Any valid JSON key No (just for json if connectorUrl is not present)
dataAttributes Data fields - for json connector if data present Object {“key1”: {“type”: “string”},… } No (just for json if connectorUrl is not present)
legend Legend for dataset. Keys for special fields Object “legend”: {“long”: “123”, “lat”: “123”, “country”: [“pais”], “region”: [“barrio”], “date”: [“startDate”, “endDate”]}} No
overwrite It allows to overwrite dataset data Boolean true/false No
published To set a public or private dataset Boolean true/false No
protected If it’s a protected layer (not is possible to delete if it’s true) Boolean true/false No
verified To generate a verified blockchain of the dataset Boolean true/false No
vocabularies Cluster of tags Object {"vocabularyOne": {"tags": [<tags>]},"vocabularyTwo": {"tags": [<tags>]}} No
widgetRelevantProps Group of relevant props of a widget Array Any Text No
layerRelevantProps Group of relevant props of a layer Array Any Text No
subscribable Available dataset queries for subscriptions parameters accepted: {{begin}} for date begin and {{end}} for date end Object {" <queryname>": "<querybodytemplate>"} No (just for json if connectorUrl is not present)

There are some differences between datasets types.

Rest-Carto datasets

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
    "connectorType":"rest",
    "provider":"cartodb",
    "connectorUrl":"<cartoUrl>",
    "application":[
     "your", "apps"
    ],
    "name":"Example Carto Dataset"
}'

A real example:

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"rest",
    "provider":"cartodb",
    "connectorUrl":"https://wri-01.carto.com/tables/wdpa_protected_areas/table",
    "application":[
     "gfw", "forest-atlas"
    ],
    "name":"World Database on Protected Areas -- Global"
}'

Rest-ArcGIS feature Service

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"rest",
    "provider":"featureservice",
    "connectorUrl":"https://services.arcgis.com/uDTUpUPbk8X8mXwl/arcgis/rest/services/Public_Schools_in_Onondaga_County/FeatureServer/0?f=json",
    "application":[
     "prep"
    ],
    "name":"Uncontrolled Public-Use Airports -- U.S."
}'

Rest-GEE

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"rest",
    "provider":"gee",
    "tableName": "JRC/GSW1_0/GlobalSurfaceWater"
    "application":[
     "rw"
    ],
    "name":"Water occurrence"
}'

Rest-NEXGDDP

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"rest",
    "provider":"nexgddp",
    "tableName": "historical/ACCESS1_0"
    "application":[
     "rw"
    ],
    "name":"Nexgddp"
}'

Rasdaman

The connectorUrl must be a URL pointing to a valid geotiff file.

curl -XPOST 'https://api.resourcewatch.org/v1/dataset' -d \
-H 'Authorization: Bearer <your-token>'  \
-H 'Content-Type: application/json' -d \
'{
    "connectorType":"rest",
    "provider":"rasdaman",
    "connectorUrl":"rw.dataset.raw/1508321309784_test_rasdaman_1b.tiff",
    "application":[
     "rw"
    ],
    "name":"rasdaman dataset"
}'

Document-CSV, Document-TSV, Document-XML

The connectorUrl must be an accessible CSV, TSV or XML file, non-compressed - zip, tar, tar.gz, etc are not supported.

CSV datasets support some optional fields on the creation process. They are:

Field Description Type Values Required
legend Object No
– lat Name of column with latitude value Text Any word No
– long Name of column with longitude value text Any word No
– date Name of columns with date value (ISO Format) Array Any list word No
– region Name of columns with region value (ISO3 code) Array Any list word No
– country Name of columns with country value (ISO3 code) Array Any list word No

z

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"document",
    "provider":"csv",
    "connectorUrl":"<csvUrl>",
    "application":[
     "your", "apps"
    ],
    "legend": {
      "lat": "lat-column",
      "long": "long-column",
      "date": ["date1Column", "date2Column"],
      "region": ["region1Column", "region2Column"],
      "country": ["country1Column", "country2Column"]
    },
    "name":"Example CSV Dataset"
}'

Real example:

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"document",
    "provider":"csv",
    "connectorUrl":"https://gfw2-data.s3.amazonaws.com/alerts-tsv/glad_headers.csv",
    "application":[
     "gfw"
    ],
    "legend": {
      "lat": "lat",
      "long": "lon"
    },
    "name":"Glad points"
}'

Document-JSON

The JSON dataset service supports data from external json file or data as json array send in request body.

The connectorUrl must be an accessible JSON file

JSON datasets support some optional fields in the creation process. They are:

Field Description Type Values Required
data JSON DATA only for json connector if connectorUrl not present Array [{},{},{}] Yes for json if connectorUrl not present
legend Object No
– lat Name of column with latitude value Text Any word No
– long Name of column with longitude value text Any word No
– date Name of columns with date value (ISO Format) Array Any list word No
– region Name of columns with region value (ISO3 code) Array Any list word No
– country Name of columns with country value (ISO3 code) Array Any list word No
curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"document",
    "provider":"json",
    "connectorUrl":"<jsonURL>",
    "application":[
     "your", "apps"
    ],
    "legend": {
      "lat": "lat-column",
      "long": "long-column",
      "date": ["date1Column", "date2Column"],
      "region": ["region1Column", "region2Column"],
      "country": ["country1Column", "country2Column"]
    },
    "name":"Example JSON Dataset",
}'

It is also possible to create a JSON dataset by including the data directly in the request:

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
    "connectorType":"document",
    "provider":"json",
    "connectorUrl":"",
    "application":[
     "your", "apps"
    ],
    "data": {"myData":[
            {"name":"nameOne", "id":"random1"},
            {"name":"nameTow", "id":"random2"}
          ]},
    "legend": {
      "lat": "lat-column",
      "long": "long-column",
      "date": ["date1Column", "date2Column"],
      "region": ["region1Column", "region2Column"],
      "country": ["country1Column", "country2Column"]
    },
    "name":"Example JSON Dataset"
}'

Uploading a Dataset (Binary)

You can upload your raw data directly to S3 making use of the “upload” endpoint. This endpoint accepts a file in the property “dataset” and returns a valid connectorUrl. With this connectorUrl you can create or update a “document” dataset, or a raster dataset in the Rasdaman adapter.

curl -X POST https://api.resourcewatch.org/v1/dataset/upload \
-H "Authorization: Bearer <your-token>" \
-F provider=csv,
-F dataset=@<your-file>

It returns the following information:

Response

{
  "connectorUrl": "rw.dataset.raw/tmp/upload_75755182b1ceda30abed717f655c077d-observed_temp.csv"
}
curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"
'{
    "connectorType":"document",
    "provider":"csv",
    "connectorUrl":"rw.dataset.raw/tmp/upload_75755182b1ceda30abed717f655c077d-observed_temp.csv",
    "application":[
     "your", "apps"
    ],
    "name":"Example RAW Data Dataset"
}'

Updating a Dataset

In order to modify the dataset, you can PATCH a request. It accepts the same parameters as the create dataset endpoint, and you will need an authentication token.

An example update request:

curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset-id> \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json" -d \
'{
    "name": "Another name for the dataset"
}'

Deleting a Dataset

When a dataset is deleted the user’s applications that were present on the dataset will be removed from it. If this results in a dataset without applications, the dataset itself will be then deleted.

curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset-id> \
-H "Authorization: Bearer <your-token>"
-H "Content-Type: application/json"

Cloning a Dataset

curl -X POST https://api.resourcewatch.org/v1/dataset/5306fd54-df71-4e20-8b34-2ff464ab28be/clone \
-H "Authorization: Bearer <your-token>"
-H "Content-Type: application/json" -d \
'{
  "dataset": {
    "datasetUrl": "/query/5306fd54-df71-4e20-8b34-2ff464ab28be?sql=select%20%2A%20from%20data%20limit%2010",
    "application": [
      "your",
      "apps"
    ]
  }
}'

Concatenate Data

You can add more data to a dataset only if the overwrite dataset property has been set to true.

Concatenate data using external data source:

curl -X POST https://api.resourcewatch.org/v1/dataset/:dataset_id/concat \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
   "connectorUrl":"<csvUrl>",
   "dataPath": "data... etc"
}'

Concatenate data using JSON array in post body:

curl -X POST https://api.resourcewatch.org/v1/dataset/:dataset_id/concat \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
   "data": [{},{}]
}'

Overwrite Data

You can overwrite the data if the overwrite dataset property has been set to true.

Overwrite data using external data source:

curl -X POST https://api.resourcewatch.org/v1/dataset/:dataset_id/data-overwrite \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
   "connectorUrl":"<url>",
   "dataPath": "data"
}'

Overwrite data using JSON array in post body:

curl -X POST https://api.resourcewatch.org/v1/dataset/:dataset_id/data-overwrite \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
   "data": [{},{}]
}'

Overwrite specific Data

You can overwrite specific data if the overwrite dataset property has been set to true.

curl -X POST https://api.resourcewatch.org/v1/dataset/:dataset_id/data/:data_id \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
'{
   "data_id":":data_id",
   "data": {"a": 1}
}'

Delete specific Data

You can delete specific data if the overwrite dataset property has been set to true.

curl -X DELETE https://api.resourcewatch.org/v1/dataset/:dataset_id/data/:data_id \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"

Dataset data sync

To sync the data of a dataset, you need to choose the action type (concat or overwrite), a cron pattern and a valid url. This configuration should be set in the 'sync’ property when creating or updating a document dataset.

Please be sure that the 'overwrite’ property is set to true. This could be used as a lock in order to not allow new updates even if the sync task is actually created.

curl -X POST https://api.resourcewatch.org/v1/dataset \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"
'{
    "connectorType":"document",
    "provider":"csv",
    "connectorUrl":"<csvUrl>",
    "application":[
     "your", "apps"
    ],
    "name":"Example SYNC Dataset",
    "overwrite": true,
    "sync": {
        "action":"concat",
        "cronPattern":"0 * * * * *",
        "url":"<updateCsvUrl>"
    }
}'

Widget

What is a Widget?

A widget is a graphic representation of a Dataset’s data. Most of them are defined with Vega grammar but we can also find other custom definitions. Here are the RW widgets definitions.

Widgets contain the following fields:

Field Description Type
userId Id of the owner Text
application Application to which the dataset belongs Array
slug Unique identifier of the widget Text
name Name of the widget Url
description Description of the widget Array
source Publisher of the original code Text
sourceUrl Link to publisher page Url
layerId UuId of the relationship with layer String
dataset UuId of the dataset that the widget belongs Text
authors Name of the authors Text
queryUrl Url with the data of the chart shows Text
widgetConfig Custom configuration Object
template If it’s a template (base schema to create other widgets) Boolean
default If it’s a default widget for the dataset that it belongs Boolean
protected If it’s a protected widget (not is possible to delete if it’s true) Boolean
status Status of the Widget Text
published If it’s available to use Text
freeze If the data is freezed Boolean
verified If it’s verified by other user Text
env Environment can be one of production or preproduction Text
thumbnailUrl Url of the widget’s thumbnail, if one exists Text

What is Vega?

Vega is a visualization grammar; a declarative format for creating, saving and sharing interactive visualization designs. This wiki contains documentation and learning materials for getting up and running with Vega. More info

How obtain all widgets

To obtain all widgets:

curl -X GET https://api.resourcewatch.org/v1/widget

Example response:

{
   "data":[
      {
         "id":"8f67fadd-d8df-4a28-82dd-a22a337d71b9",
         "type":"widget",
         "attributes":{
            "userId":"5858f37140621f11066fb2f7",
            "application":[
               "aqueduct"
            ],
            "slug":"percentage-of-country-s-population-is-at-high-risk-of-hunger",
            "name":"Percentage of country's population at high risk of hunger.",
            "description":"",
            "source":"",
            "sourceUrl":"",
            "layerId":null,
            "dataset":"f1d24950-c764-4f90-950a-4541f798eb95",
            "authors":"",
            "queryUrl":"query/f1d24950-c764-4f90-950a-4541f798eb95?sql=select * from crops",
            "widgetConfig":{
                ...
            },
            "template":false,
            "default":true,
            "status":"saved",
            "published":true,
            "freeze": false,
            "verified":false
         }
      }
   ],
   "links":{
      "first":"https://api.resourcewatch.org/v1/widget?page%5Bnumber%5D=1",
      "prev":"https://api.resourcewatch.org/v1/widget?page%5Bnumber%5D=1",
      "next":"https://api.resourcewatch.org/v1/widget?page%5Bnumber%5D=2&page%5Bsize%5D=10",
      "last":"https://api.resourcewatch.org/v1/widget?page%5Bnumber%5D=64&page%5Bsize%5D=10",
      "self":"https://api.resourcewatch.org/v1/widget?page%5Bnumber%5D=1&page%5Bsize%5D=10"
   },
   "meta": {
      "total-pages": 38,
      "total-items": 372,
      "size": 10
   }
}

Filter params

Available filters:

Field Description Type
name Filter the widgets whose name contains the filter text Text
dataset Filter the widgets by dataset uuid Text
sort Sort json response by specific attributes Text
status Filter widgets on status (pending, saved, failed, all) Text
published Filter widgets on published status (true, false) Boolean
published Filter widgets on freeze status (true, false) Boolean
verified Filter by verified status (true, false) Boolean
template Filter by template status (true, false) Boolean
default Filter by default status (true, false) Boolean
app Filter widgets on application (prep, gfw, etc..) Text
env Environment can be one of production or preproduction Text

Return the widgets filtered whose name contains glad

curl -X GET https://api.resourcewatch.org/v1/widget?name=glad

Return the widgets filtered by dataset

curl -X GET https://api.resourcewatch.org/v1/widget?dataset=d02df2f6-d80c-4274-bb6f-f062061655c4
curl -X GET https://api.resourcewatch.org/v1/dataset/d02df2f6-d80c-4274-bb6f-f062061655c4/widget

Sort by name

curl -X GET https://api.resourcewatch.org/v1/widget?sort=name

Filter widgets by status

curl -X GET https://api.resourcewatch.org/v1/widget?status=failed

Filter widgets by published status

curl -X GET https://api.resourcewatch.org/v1/widget?published=false

Filter widgets by verified status

curl -X GET https://api.resourcewatch.org/v1/widget?verified=false

Return the widgets filtered by template

curl -X GET https://api.resourcewatch.org/v1/widget?template=true

Filter widgets by default option

curl -X GET https://api.resourcewatch.org/v1/widget?default=true

Return widgets whose applications contain rw

curl -X GET https://api.resourcewatch.org/v1/widget?app=rw

Pagination params

Field Description Type
page[size] Number elements per page Number
page[number] Number of page Number

Return the widgets from page 2, with 5 elements per page

curl -X GET https://api.resourcewatch.org/v1/widget?page[size]=5&page[number]=2

How obtain a widget for a specific dataset

To obtain the widget:

curl -X GET https://api.resourcewatch.org/v1/dataset/d02df2f6-d80c-4274-bb6f-f062061655c4/widget/20ec7861-5251-40a7-9503-5ee3686a66a3
curl -X GET https://api.resourcewatch.org/v1/widget/20ec7861-5251-40a7-9503-5ee3686a66a3

Example response:

{
  "data": {
    "id": "20ec7861-5251-40a7-9503-5ee3686a66a3",
    "type": "widget",
    "attributes": {
      "userId": "57a0693b49c36b265ba3bec8",
      "application": [
        "rw"
      ],
      "slug": "estimated-c02-emission",
      "name": "Estimated C02 emission",
      "description": null,
      "source": "",
      "sourceUrl": null,
      "layerId": null,
      "dataset": "d02df2f6-d80c-4274-bb6f-f062061655c4",
      "authors": null,
      "queryUrl": "query/d02df2f6-d80c-4274-bb6f-f062061655c4?sql=select country, rank, iso3, total from estimated_co2_emission_filtered",
      "widgetConfig": {
        "data": [
          {
            "name": "table",
            "values": [],
            "transform": [
              {
                "by": "rank",
                "type": "sort"
              }
            ]
          },
          {
            "name": "current",
            "source": "table",
            "transform": [
              {
                "test": "datum.iso3 === 'CHN'",
                "type": "filter"
              },
              {
                "expr": "datum.rank",
                "type": "formula",
                "field": "current_rank"
              }
            ]
          },
          {
            "name": "max",
            "source": "table",
            "transform": [
              {
                "type": "aggregate",
                "summarize": {
                  "rank": [
                    "max"
                  ]
                }
              }
            ]
          },
          {
            "name": "head",
            "source": "table",
            "transform": [
              {
                "type": "cross",
                "with": "current"
              },
              {
                "test": "datum.b.current_rank <= 5 ? datum.a.rank <= 5 : datum.a.rank === 1",
                "type": "filter"
              },
              {
                "expr": "datum.a.rank === datum.b.current_rank ? '#5BB1D2' : '#9aa2a9'",
                "type": "formula",
                "field": "color"
              },
              {
                "expr": "datum.a.rank === datum.b.current_rank ? '500' : '300'",
                "type": "formula",
                "field": "weight"
              }
            ]
          },
          {
            "name": "head_count",
            "source": "head",
            "transform": [
              {
                "type": "aggregate",
                "summarize": {
                  "*": "count"
                }
              }
            ]
          },
          {
            "name": "center",
            "source": "table",
            "transform": [
              {
                "type": "cross",
                "with": "current"
              },
              {
                "type": "cross",
                "with": "max"
              },
              {
                "test": "datum.a.b.current_rank > 5 && datum.a.b.current_rank < datum.b.max_rank - 5 ? datum.a.a.rank >= datum.a.b.current_rank - 2 && datum.a.a.rank <= datum.a.b.current_rank + 2  : false",
                "type": "filter"
              },
              {
                "expr": "datum.a.a.rank === datum.a.b.current_rank ? '#5BB1D2' : '#9aa2a9'",
                "type": "formula",
                "field": "color"
              },
              {
                "expr": "datum.a.a.rank === datum.a.b.current_rank ? '500' : '300'",
                "type": "formula",
                "field": "weight"
              }
            ]
          },
          {
            "name": "center_count",
            "source": "center",
            "transform": [
              {
                "type": "aggregate",
                "summarize": {
                  "*": "count"
                }
              }
            ]
          },
          {
            "name": "tail",
            "source": "table",
            "transform": [
              {
                "type": "cross",
                "with": "current"
              },
              {
                "type": "cross",
                "with": "max"
              },
              {
                "test": "datum.a.b.current_rank >= datum.b.max_rank - 4 ? datum.a.a.rank >= datum.b.max_rank - 4 : datum.a.a.rank === datum.b.max_rank",
                "type": "filter"
              },
              {
                "expr": "datum.a.a.rank === datum.a.b.current_rank ? '#5BB1D2' : '#9aa2a9'",
                "type": "formula",
                "field": "color"
              },
              {
                "expr": "datum.a.b.current_rank <= 5 || datum.a.b.current_rank >= datum.b.max_rank - 4 ? datum.color : 'transparent'",
                "type": "formula",
                "field": "trick_color"
              },
              {
                "expr": "datum.a.b.current_rank <= 5 || datum.a.b.current_rank >= datum.b.max_rank - 4 ? '#9aa2a9' : 'transparent'",
                "type": "formula",
                "field": "rule_trick_color"
              },
              {
                "expr": "datum.a.a.rank === datum.a.b.current_rank ? '500' : '300'",
                "type": "formula",
                "field": "weight"
              }
            ]
          }
        ],
        "marks": [
          {
            "from": {
              "data": "head"
            },
            "type": "text",
            "properties": {
              "enter": {
                "x": {
                  "value": 20
                },
                "y": {
                  "field": "a.rank",
                  "scale": "vertical_head"
                },
                "fill": {
                  "field": "color"
                },
                "text": {
                  "template": "{{datum.a.rank}}"
                },
                "align": {
                  "value": "right"
                },
                "baseline": {
                  "value": "middle"
                },
                "fontSize": {
                  "value": 13
                },
                "fontWeight": {
                  "field": "weight"
                }
              }
            }
          },
          {
            "from": {
              "data": "head"
            },
            "type": "text",
            "properties": {
              "enter": {
                "x": {
                  "value": 30
                },
                "y": {
                  "field": "a.rank",
                  "scale": "vertical_head"
                },
                "fill": {
                  "field": "color"
                },
                "text": {
                  "template": "{{datum.a.country | truncate:10}}"
                },
                "align": {
                  "value": "left"
                },
                "baseline": {
                  "value": "middle"
                },
                "fontSize": {
                  "value": 13
                },
                "fontWeight": {
                  "field": "weight"
                }
              }
            }
          },
          {
            "from": {
              "data": "head"
            },
            "type": "rect",
            "properties": {
              "enter": {
                "x": {
                  "mult": 0.5,
                  "field": {
                    "group": "width"
                  }
                },
                "y": {
                  "field": "a.rank",
                  "scale": "vertical_head",
                  "offset": -6
                },
                "fill": {
                  "field": "color"
                },
                "width": {
                  "mult": 0.5,
                  "field": "a.total",
                  "scale": "bar"
                },
                "height": {
                  "value": 12
                }
              }
            }
          },
          {
            "from": {
              "data": "head_count"
            },
            "type": "group",
            "marks": [
              {
                "type": "rule",
                "properties": {
                  "enter": {
                    "x": {
                      "value": 0
                    },
                    "y": {
                      "value": 0,
                      "offset": -15
                    },
                    "x2": {
                      "field": {
                        "group": "width"
                      }
                    },
                    "stroke": {
                      "value": "#9aa2a9"
                    },
                    "strokeWidth": {
                      "value": 0.5
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "center"
                },
                "type": "text",
                "properties": {
                  "enter": {
                    "x": {
                      "value": 20
                    },
                    "y": {
                      "scale": "vertical_center",
                      "fimeld": "a.a.rank"
                    },
                    "fill": {
                      "field": "color"
                    },
                    "text": {
                      "template": "{{datum.a.a.rank}}"
                    },
                    "align": {
                      "value": "right"
                    },
                    "baseline": {
                      "value": "middle"
                    },
                    "fontSize": {
                      "value": 13
                    },
                    "fontWeight": {
                      "field": "weight"
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "center"
                },
                "type": "text",
                "properties": {
                  "enter": {
                    "x": {
                      "value": 30
                    },
                    "y": {
                      "field": "a.a.rank",
                      "scale": "vertical_center"
                    },
                    "fill": {
                      "field": "color"
                    },
                    "text": {
                      "template": "{{datum.a.a.country | truncate:20}}"
                    },
                    "align": {
                      "value": "left"
                    },
                    "baseline": {
                      "value": "middle"
                    },
                    "fontSize": {
                      "value": 13
                    },
                    "fontWeight": {
                      "field": "weight"
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "center"
                },
                "type": "rect",
                "properties": {
                  "enter": {
                    "x": {
                      "mult": 0.5,
                      "field": {
                        "group": "width"
                      }
                    },
                    "y": {
                      "field": "a.a.rank",
                      "scale": "vertical_center",
                      "offset": -6
                    },
                    "fill": {
                      "field": "color"
                    },
                    "width": {
                      "mult": 0.5,
                      "field": "a.a.total",
                      "scale": "bar"
                    },
                    "height": {
                      "value": 12
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "center_count"
                },
                "type": "group",
                "marks": [
                  {
                    "type": "rule",
                    "properties": {
                      "enter": {
                        "x": {
                          "value": 0
                        },
                        "y": {
                          "value": 0,
                          "offset": -15
                        },
                        "x2": {
                          "field": {
                            "group": "width"
                          }
                        },
                        "stroke": {
                          "value": "#9aa2a9"
                        },
                        "strokeWidth": {
                          "value": 0.5
                        }
                      }
                    }
                  },
                  {
                    "from": {
                      "data": "tail"
                    },
                    "type": "text",
                    "properties": {
                      "enter": {
                        "x": {
                          "value": 20
                        },
                        "y": {
                          "field": "a.a.rank",
                          "scale": "vertical_tail"
                        },
                        "fill": {
                          "field": "color"
                        },
                        "text": {
                          "template": "{{datum.a.a.rank}}"
                        },
                        "align": {
                          "value": "right"
                        },
                        "baseline": {
                          "value": "middle"
                        },
                        "fontSize": {
                          "value": 13
                        },
                        "fontWeight": {
                          "field": "weight"
                        }
                      }
                    }
                  },
                  {
                    "from": {
                      "data": "tail"
                    },
                    "type": "text",
                    "properties": {
                      "enter": {
                        "x": {
                          "value": 30
                        },
                        "y": {
                          "field": "a.a.rank",
                          "scale": "vertical_tail"
                        },
                        "fill": {
                          "field": "color"
                        },
                        "text": {
                          "template": "{{datum.a.a.country | truncate:20}}"
                        },
                        "align": {
                          "value": "left"
                        },
                        "baseline": {
                          "value": "middle"
                        },
                        "fontSize": {
                          "value": 13
                        },
                        "fontWeight": {
                          "field": "weight"
                        }
                      }
                    }
                  },
                  {
                    "from": {
                      "data": "tail"
                    },
                    "type": "rect",
                    "properties": {
                      "enter": {
                        "x": {
                          "mult": 0.5,
                          "field": {
                            "group": "width"
                          }
                        },
                        "y": {
                          "field": "a.a.rank",
                          "scale": "vertical_tail",
                          "offset": -6
                        },
                        "fill": {
                          "field": "color"
                        },
                        "width": {
                          "mult": 0.5,
                          "field": "a.a.total",
                          "scale": "bar"
                        },
                        "height": {
                          "value": 12
                        }
                      }
                    }
                  }
                ],
                "properties": {
                  "enter": {
                    "y": {
                      "mult": 20,
                      "field": "count",
                      "offset": 10
                    },
                    "width": {
                      "field": {
                        "group": "width"
                      }
                    }
                  }
                }
              }
            ],
            "properties": {
              "enter": {
                "x": {
                  "value": 0
                },
                "y": {
                  "mult": 20,
                  "field": "count",
                  "offset": 10
                },
                "width": {
                  "field": {
                    "group": "width"
                  }
                }
              }
            }
          },
          {
            "from": {
              "data": "head_count"
            },
            "type": "group",
            "marks": [
              {
                "from": {
                  "data": "tail"
                },
                "type": "rule",
                "properties": {
                  "enter": {
                    "x": {
                      "value": 0
                    },
                    "y": {
                      "value": 0,
                      "offset": -15
                    },
                    "x2": {
                      "field": {
                        "group": "width"
                      }
                    },
                    "stroke": {
                      "field": "rule_trick_color"
                    },
                    "strokeWidth": {
                      "value": 0.5
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "tail"
                },
                "type": "text",
                "properties": {
                  "enter": {
                    "x": {
                      "value": 20
                    },
                    "y": {
                      "field": "a.a.rank",
                      "scale": "vertical_tail"
                    },
                    "fill": {
                      "field": "trick_color"
                    },
                    "text": {
                      "template": "{{datum.a.a.rank}}"
                    },
                    "align": {
                      "value": "right"
                    },
                    "baseline": {
                      "value": "middle"
                    },
                    "fontSize": {
                      "value": 13
                    },
                    "fontWeight": {
                      "field": "weight"
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "tail"
                },
                "type": "text",
                "properties": {
                  "enter": {
                    "x": {
                      "value": 30
                    },
                    "y": {
                      "field": "a.a.rank",
                      "scale": "vertical_tail"
                    },
                    "fill": {
                      "field": "trick_color"
                    },
                    "text": {
                      "template": "{{datum.a.a.country | truncate:20}}"
                    },
                    "align": {
                      "value": "left"
                    },
                    "baseline": {
                      "value": "middle"
                    },
                    "fontSize": {
                      "value": 13
                    },
                    "fontWeight": {
                      "field": "weight"
                    }
                  }
                }
              },
              {
                "from": {
                  "data": "tail"
                },
                "type": "rect",
                "properties": {
                  "enter": {
                    "x": {
                      "mult": 0.5,
                      "field": {
                        "group": "width"
                      }
                    },
                    "y": {
                      "field": "a.a.rank",
                      "scale": "vertical_tail",
                      "offset": -6
                    },
                    "fill": {
                      "field": "trick_color"
                    },
                    "width": {
                      "mult": 0.5,
                      "field": "a.a.total",
                      "scale": "bar"
                    },
                    "height": {
                      "value": 12
                    }
                  }
                }
              }
            ],
            "properties": {
              "enter": {
                "y": {
                  "mult": 20,
                  "field": "count",
                  "offset": 10
                },
                "width": {
                  "field": {
                    "group": "width"
                  }
                }
              }
            }
          }
        ],
        "scales": [
          {
            "name": "vertical_head",
            "type": "ordinal",
            "range": [
              0,
              20,
              40,
              60,
              80
            ],
            "domain": {
              "data": "head",
              "sort": {
                "op": "min",
                "field": "a.rank"
              },
              "field": "a.rank"
            }
          },
          {
            "name": "vertical_center",
            "type": "ordinal",
            "range": [
              0,
              20,
              40,
              60,
              80
            ],
            "domain": {
              "data": "center",
              "sort": {
                "op": "min",
                "field": "a.a.rank"
              },
              "field": "a.a.rank"
            }
          },
          {
            "name": "vertical_tail",
            "type": "ordinal",
            "range": [
              0,
              20,
              40,
              60,
              80
            ],
            "domain": {
              "data": "tail",
              "sort": {
                "op": "min",
                "field": "a.a.rank"
              },
              "field": "a.a.rank"
            }
          },
          {
            "name": "bar",
            "type": "linear",
            "range": "width",
            "domain": {
              "data": "table",
              "field": "total"
            }
          }
        ],
        "padding": {
          "top": 40,
          "left": 20,
          "right": 20,
          "bottom": 0
        }
      },
      "template": false,
      "default": false,
      "status": "saved",
      "published": true,
      "verified": false
    }
  },
  "meta": {
    "status": "saved",
    "published": true,
    "verified": false,
    "updated_at": "2017-01-17T17:50:45.655Z",
    "created_at": "2016-06-06T15:12:38.749Z"
  }
}

Modify the Query Url of a widget

The queryUrl query parameter can be set if the user needs to modify the final url that will be requested. All parameters indicated in the queryUrl, will be pass to the microservice.

curl -X GET https://api.resourcewatch.org/v1/widget/049f074a-3528-427d-922b-3c2320e9caf6?queryUrl=/v1/query?sql=Select%20*%20from%20data&geostore=ungeostore

Create a Widget

To create a widget, you need to define all of the required fields in the request body. The fields that compose a widget are:

Field Description Type Values Required
name Name of the widget Text Any Text Yes
description Description of the dataset Text Any text No
source Publisher of the original code Text Any text No
sourceUrl Link to publisher page Text Any url No
application Application to which the widget belongs Array gfw, forest-atlas, rw, prep, aqueduct, data4sdg Yes
authors Name of the authors Text Any text No
queryUrl Url with the data of the chart shows Text Any valid query No
widgetConfig Vega configuration Object Valid object No
status Status of the Widget Number 1 No
published If it’s available to use Boolean true - false No
freeze If the data is freezed Boolean true - false No
protected If it’s a protected widget (not is possible to delete if it’s true) Boolean true - false No
verified If it’s verified by other user Boolean true - false No
template If it’s a template Boolean true - false No
default If it’s default for dataset Boolean true - false No
layerId UuId of the relationship with layer Text Uuid of layer No
dataset UuId of the dataset Text Uuid of Dataset No

To create a widget, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset_id>/widget \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "widget": {
      "application":[
         "your", "apps"
      ],
      "name":"Example Carto Dataset"
      "status": 1,
      "published": true
   }
}'

Update a Widget

To update a widget, you need to define all of the required fields in the request body. The fields that compose a widget are:

Field Description Type Values Required
name Name of the widget Text Any Text Yes
description Description of the dataset Text Any text No
source Publisher of the original code Text Any text No
sourceUrl Link to publisher page Text Any url No
application Application to which the widget belongs Array gfw, forest-atlas, rw, prep, aqueduct, data4sdg Yes
authors Name of the authors Text Any text No
queryUrl Url with the data of the chart shows Text Any valid query No
widgetConfig Vega configuration Object Valid object No
status Status of the Widget Number 1 No
published If it’s available to use Boolean true - false No
freeze If the data is freezed Boolean true - false No
verified If it’s verified by other user Boolean true - false No
template If it’s a template Boolean true - false No
default If it’s default for dataset Boolean true - false No
layerId UuId of the relationship with layer Text Uuid of layer No
dataset UuId of the dataset Text Uuid of Dataset No
env Environment Text production or preproduction Yes

To update a widget, you have to do a PATCH request with the following body:

curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset_id>/widget/<widget_id> \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "widget": {
      "application":[
         "your", "apps"
      ],
      "name":"New Example Carto Dataset Name",
      "widgetConfig": {}
   }
}'

Clone a Widget

You can clone an existing widget as long as you have permissions to the applications associated with it. Basic usage requires no body params, but you can optionally pass a new name or description to be used in the creation of the new widget.

To clone a widget, you should use one of the following POST requests:

curl -X POST https://api.resourcewatch.org/v1/widget/<widget_id>/clone \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset_id>/widget/<widget_id>/clone \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"

You can optionally set a new name or description:

curl -X POST https://api.resourcewatch.org/v1/widget/<widget_id>/clone \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "name for the cloned widget",
   "description": "
   "name": "name for the cloned widget", for the cloned widget",
}'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset_id>/widget/<widget_id>/clone \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "name for the cloned widget",
   "description": "
   "name": "name for the cloned widget", for the cloned widget",
}'

Delete a Widget

curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset_id>/widget/<widget_id> \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"

Layer

What is a Layer?

A layer is a geographical representation of a Dataset’s data.

Layer contains the following fields:

Field Description Type
userId Id of the owner Text
application Application to which the dataset belongs Array
iso The isos to which the dataset belongs Array
slug Unique identifier of the layer Text
name Name of the layer Url
description Description of the layer Array
dataset UuId of the dataset that the layer belongs Text
layerConfig Custom configuration Object
legendConfig Custom configuration Object
applicationConfig Custom configuration Object
staticImageConfig Custom configuration Object
default If it’s a default layer for the dataset that it belongs Boolean
protected If it’s a protected layer (not is possible to delete if it’s true) Boolean
published Is the layer published? Boolean
env environment in witch the layer was published, one of preproduction or production Text

How obtain all layers

To obtain all layers:

curl -X GET https://api.resourcewatch.org/v1/layer

Example response:

{
   "data":[
      {
        "id": "e5c3e7c5-19ae-4ca0-a461-71f1f67aa553",
        "type": "layer",
        "attributes": {
          "slug": "total-co2-emissions-by-year",
          "userId": "5858f37140621f11066fb2f7",
          "application": [
            "rw"
          ],
          "name": "Total CO2 emissions by year",
          "default": false,
          "dataset": "11de2bc1-368b-42ed-a207-aaff8ece752b",
          "provider": "cartodb",
          "iso": [],
          "description": null,
          "layerConfig": {
            "account": "rw",
            "body": {
              "maxzoom": 18,
              "minzoom": 3,
              "layers": [
                {
                  "type": "mapnik",
                  "options": {
                    "sql": "SELECT * cait_2_0_country_ghg_emissions_filtered",
                    "cartocss": "",
                    "cartocss_version": "2.3.0"
                  }
                }
              ]
            }
          },
          "legendConfig": {
            "marks": {
              "type": "rect",
              "from": {
                "data": "table"
              }
            }
          },
          "applicationConfig": {},
          "staticImageConfig": {}
        }
      }
   ],
   "links":{
      "first":"https://api.resourcewatch.org/v1/layer?page%5Bnumber%5D=1",
      "prev":"https://api.resourcewatch.org/v1/layer?page%5Bnumber%5D=1",
      "next":"https://api.resourcewatch.org/v1/layer?page%5Bnumber%5D=2&page%5Bsize%5D=10",
      "last":"https://api.resourcewatch.org/v1/layer?page%5Bnumber%5D=64&page%5Bsize%5D=10",
      "self":"https://api.resourcewatch.org/v1/layer?page%5Bnumber%5D=1&page%5Bsize%5D=10"
   },
   "meta": {
      "total-pages": 63,
      "total-items": 628,
      "size": 10
   }
}

Filter params

Available filters:

Field Description Type
name Filter the layers whose name contains the filter text Text
dataset Filter the layers by dataset uuid Text
sort Sort json response by specific attributes Text
status Filter layers on status (pending, saved, failed, all) Text
published Filter layers on published status (true, false) Boolean
app Filter layers on application (prep, gfw, etc..) Text
env Environment in witch the layer was published, one of preproduction or production Text

Return the layers filtered by those whose name contains emissions

curl -X GET https://api.resourcewatch.org/v1/layer?name=emissions

Return the layers filtered by dataset

curl -X GET https://api.resourcewatch.org/v1/layer?dataset=11de2bc1-368b-42ed-a207-aaff8ece752b
curl -X GET https://api.resourcewatch.org/v1/dataset/11de2bc1-368b-42ed-a207-aaff8ece752b/layer

Sort by name

curl -X GET https://api.resourcewatch.org/v1/layer?sort=name

Filter layers by status

curl -X GET https://api.resourcewatch.org/v1/layer?status=failed

Filter layers by published status

curl -X GET https://api.resourcewatch.org/v1/layer?published=false

Return the layers filtered by those whose applications contain rw

curl -X GET https://api.resourcewatch.org/v1/layer?app=rw

Pagination params

Field Description Type
page[size] Number elements per page Number
page[number] Number of page Number

Return the layers of page 2 with 5 elements per page

curl -X GET https://api.resourcewatch.org/v1/layer?page[size]=5&page[number]=2

How obtain a layer for specific dataset

To obtain the layer:

curl -X GET https://api.resourcewatch.org/v1/dataset/11de2bc1-368b-42ed-a207-aaff8ece752b/layer/e5c3e7c5-19ae-4ca0-a461-71f1f67aa553
curl -X GET https://api.resourcewatch.org/v1/layer/e5c3e7c5-19ae-4ca0-a461-71f1f67aa553

Example response:

{
  "data": {
    "id": "e5c3e7c5-19ae-4ca0-a461-71f1f67aa553",
    "type": "layer",
    "attributes": {
      "slug": "total-co2-emissions-by-year",
      "userId": "5858f37140621f11066fb2f7",
      "application": [
        "rw"
      ],
      "name": "Total CO2 emissions by year",
      "default": false,
      "dataset": "11de2bc1-368b-42ed-a207-aaff8ece752b",
      "provider": "cartodb",
      "iso": [],
      "description": null,
      "layerConfig": {
        "account": "rw",
        "body": {
          "maxzoom": 18,
          "minzoom": 3,
          "layers": [
            {
              "type": "mapnik",
              "options": {
                "sql": "SELECT * cait_2_0_country_ghg_emissions_filtered",
                "cartocss": "",
                "cartocss_version": "2.3.0"
              }
            }
          ]
        }
      },
      "legendConfig": {
        "marks": {
          "type": "rect",
          "from": {
            "data": "table"
          }
        }
      },
      "applicationConfig": {},
      "staticImageConfig": {}
    }
  },
  "meta": {
    "status": "saved",
    "published": true,
    "updatedAt": "2017-01-23T16:51:42.571Z",
    "createdAt": "2017-01-23T16:51:42.571Z"
  }
}

Create a Layer

To create a layer, you need to define all of the required fields in the request body. The fields that compose a layer are:

Field Description Type Values Required
name Name of the layer Text Any Text Yes
description Description of the dataset Text Any text No
application Application to which the layer belongs Array gfw, forest-atlas, rw, prep, aqueduct, data4sdg Yes
layerConfig Custom configuration, rw definition example Object Valid object No
legendConfig Custom configuration Object Valid object No
applicationConfig Custom configuration Object Valid object No
staticImageConfig Custom configuration Object Valid object No
iso Isos to which the layer belongs Array BRA, ES No
dataset UuId of the dataset Text Uuid of Dataset No
protected If it’s a protected layer (not is possible to delete if it’s true) Boolean true-false No

To create a layer, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset_id>/layer \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
    "application":[
       "your", "apps"
    ],
    "name":"Example layer",
    "status": 1
}'

The following structure was previously supported but should now be considered deprecated:

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset_id>/layer \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "layer": {
      "application":[
         "your", "apps"
      ],
      "name":"Example layer",
      "status": 1
   }
}'

Update a Layer

To update a layer, you need to define all of the required fields in the request body. The fields that compose a layer are:

Field Description Type Values Required
name Name of the layer Text Any Text Yes
description Description of the dataset Text Any text No
application Application to which the layer belongs Array gfw, forest-atlas, rw, prep, aqueduct, data4sdg Yes
layerConfig Custom configuration Object Valid object No
legendConfig Custom configuration Object Valid object No
applicationConfig Custom configuration Object Valid object No
staticImageConfig Custom configuration Object Valid object No
iso The isos to which the layer belongs Array BRA, ES No
dataset UuId of the dataset Text Uuid of Dataset No

To create a layer, you have to do a POST requestwith the following body:

curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset_id>/layer/<layer_id> \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "layer": {
      "application":[
         "your", "apps"
      ],
      "name":"New Example layer Name",
      "layerConfig": {}
   }
}'

Delete a Layer

curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset_id>/layer/<layer_id> \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"

Query

In order to retrieve data from the datasets it is possible to send queries to the API using the SQL or Feature Service languages.

Two different endpoints are provided (under the dataset path and a generic one) and the sql query can be provided via query parameters or in the body of a POST request.

curl -i -H 'Authorization: Bearer your-token>' -H 'Content-Type: application/json' -XPOST 'http://api.resourcewatch.org/v1/query/<dataset_id>/' -d '{
    "sql": "SELECT * FROM <dataset_id> limit 10"
}
'
curl -i -XGET http\://api.resourcewatch.org/v1/query\?sql\=SELECT\ \*\ from\ <dataset.slug>

Select clause

The SELECT part of the queries supports naming columns, alias, math operations, DISTINCT, COUNT, SQL functions and PostGIS functions

SELECT * FROM table
SELECT count(*) FROM table
SELECT a, b FROM table
SELECT a, count(*) FROM table

SELECT sum(int) FROM table
SELECT avg(int) FROM table
SELECT max(int) FROM table
SELECT min(int) FROM table
SELECT min(int) as minimum FROM table

SELECT ST_valueCount(rast, 1, true) FROM table

From clause

It is possible to refer to a dataset by using its table name, slug or id.

SELECT * FROM <dataset.tableName>
SELECT * FROM <dataset.slug>
SELECT * FROM <dataset.id>

Where clause

SELECT * FROM table WHERE a > 2
SELECT * FROM table WHERE a = 2
SELECT * FROM table WHERE a < 2
SELECT * FROM table WHERE a >= 2
SELECT * FROM table WHERE a = 2 and b < 2
SELECT * FROM table WHERE text like 'a%'
SELECT * FROM table WHERE st_intersects(st_setsrid(st_geomfromgeojson('{}'), 4326), the_geom)
SELECT * FROM table WHERE data BETWEEN 1 AND 3

Group by clause

It is possible to group results by column name, SQL functions and PostGIS functions. Special grouping operations are available for document-type datasets (CSV and JSON) - see this link for more info.

SELECT * FROM tablename GROUP BY columnOne
SELECT * FROM tablename GROUP BY columnOne, columnTwo
SELECT * FROM tablename GROUP BY ST_GeoHash(the_geom_point,8)

SELECT a, count(int) FROM table GROUP BY a
SELECT count(*) FROM tablename GROUP BY ST_GeoHash(the_geom, 8)
/* Only supported in document-type datasets - see https://github.com/NLPchina/elasticsearch-sql/tree/5.5.2.0#beyond-sql for full details */
SELECT COUNT(age) FROM tablename GROUP BY range(age, 20,25,30,35,40) 
SELECT online FROM online GROUP BY date_histogram(field='insert_time','interval'='1d')
SELECT online FROM online GROUP BY date_range(field='insert_time','format'='yyyy-MM-dd' ,'2014-08-18','2014-08-17','now-8d','now-7d','now-6d','now')

Order by clause

It is possible to order results by column name, SQL functions and PostGIS functions

Limit and offset clause

You can specify limit and offset clauses

SELECT * FROM table limit=20
SELECT * FROM table limit=20 offset 10

Raster queries available

SELECT ST_METADATA(rast) FROM table
SELECT ST_BANDMETADATA(rast, occurrence) FROM table
SELECT ST_SUMMARYSTATS() FROM table
SELECT ST_HISTOGRAM(rast, 1, auto, true) FROM table
SELECT ST_valueCount(rast, 1, true) FROM table

Freeze query

It is possible generate a json file in a bucket of the sql result. You only need send a query param freeze with value true and you will obtain the url of the json file.

curl -i -XGET http\://api.resourcewatch.org/v1/query\?sql\=SELECT\ \*\ from\ <dataset.slug>&freeze=true

Rasdaman queries

SQL-like queries can be employed for accessing data stored in Rasdaman datasets. Subsets on the original axes of the data may be provided in the WHERE statement. So far, only operations that result in a single scalar can be obtained from Rasdaman - averages, minimums, maximums.

curl -XGET https://api.resourcewatch.org/v1/query?sql=SELECT avg(Green) from 18c0b71d-2f55-4a45-9e5b-c35db3ebfe94 where Lat > 0 and  Lat < 45 \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer <token>'

NEX-GDDP queries

A SQL wrapper is offered for accessing the NASA NEX-GDDP dataset with sql-like statements. The API stores calculated indexes over the original data, and several views over the data are available. These can be accessed in the following ways:

Spatial aggregates over a layer

Access spatial aggregates over the data by listing all dataset data for a particular year:

curl -i -XGET http\://api.resourcewatch.org/v1/query/b99c5f5e-00c6-452e-877c-ced2b9f0b393\?sql\=SELECT\ \*\ from\ nexgddp-historical-ACCESS1_0-prmaxday\ where\ year\ \=\ 1960

Access particular aggregates:

curl -i -XGET http\://api.resourcewatch.org/v1/query/b99c5f5e-00c6-452e-877c-ced2b9f0b393\?sql\=SELECT\ avg\,\ min\ from\ nexgddp-historical-ACCESS1_0-prmaxday\ where\ year\ \=\ 1960

Calculate statistics for a range of years:

curl -i -XGET http\://api.resourcewatch.org/v1/query/b99c5f5e-00c6-452e-877c-ced2b9f0b393\?sql\=SELECT\ \*\ from\ nexgddp-historical-ACCESS1_0-prmaxday\ \ where\ year\ between\ 1960\ and\ 1962

You can delimit an area of interest by providing a geostore id as a parameter:

curl -i -XGET http\://api.resourcewatch.org/v1/query/b99c5f5e-00c6-452e-877c-ced2b9f0b393\?sql\=SELECT\ \*\ from\ nexgddp-historical-ACCESS1_0-prmaxday\ \ where\ year\ between\ 1960\ and\ 1962&geostore\=0279093c278a64f4c3348ff63e4cfce0

Jiminy

Jiminy is a lightweight library that powers this api endopoint whose aim is to infer which type of charts can be obtained from a dataset.

To get the jiminy information from a query, you can do the following request:

/jiminy?sql=select <columns> from <dataset.slug or dataset.id> limit <number>

In order to retrieve the mentioned information the name of the columns that you want to obtain the data from are required.

To obtain jiminy information, you have to do a GET with the following query params:

curl -X GET https://api.resourcewatch.org/v1/jiminy?sql=select <columns> from <dataset.slug or dataset.id> \
-H "Content-Type: application/json"

It is possible do a POST too:

curl -X POST https://api.resourcewatch.org/v1/jiminy \
-H "Content-Type: application/json"  -d \
 '{
   "sql": "select <columns> from <dataset.slug or dataset.id>"
  }'

Real example

curl -X GET https://api.resourcewatch.org/v1/jiminy?sql=select satellite, confidence, track, acq_date from VIIRS-Active-Fire-Global-1490086842549 limit 1000 \
-H "Content-Type: application/json"

The response will be 200 if the query is correct:


{
  "data": {
    "general": ["bar", "line", "pie", "scatter", "1d_scatter", "1d_tick"],
    "byColumns": {
      "satellite": ["bar", "pie"],
      "confidence": ["bar", "pie"],
      "track": ["1d_scatter", "1d_tick"],
      "acq_date": ["1d_scatter", "1d_tick"]
    },
    "byType": {
      "bar": {
        "general": ["satellite", "confidence", "track"],
        "columns": {
          "satellite": ["track"],
          "confidence": ["track"],
          "track": ["satellite", "confidence", "acq_date"],
          "acq_date": ["track"]
        }
      },
      "line": {
        "general": ["track"],
        "columns": {
          "satellite": [],
          "confidence": [],
          "track": ["acq_date"],
          "acq_date": ["track"]
        }
      },
      "pie": {
        "general": ["satellite", "confidence"],
        "columns": {
          "satellite": [],
          "confidence": [],
          "track": [],
          "acq_date": []
        }
      },
      "scatter": {
        "general": ["satellite", "confidence"],
        "columns": {
          "satellite": ["confidence"],
          "confidence": ["satellite"],
          "track": ["satellite", "confidence"],
          "acq_date": ["satellite", "confidence"]
        }
      },
      "1d_scatter": {
        "general": ["track", "acq_date"],
        "columns": {
          "satellite": [],
          "confidence": [],
          "track": [],
          "acq_date": []
        }
      },
      "1d_tick": {
        "general": ["track", "acq_date"],
        "columns": {
          "satellite": [],
          "confidence": [],
          "track": [],
          "acq_date": []
        }
      }
    }
  }
}

Fields

What are fields?

Fields can be defined as the dataset properties. These fields are automatically generated when a dataset is created.

How to get the dataset fields

Once the dataset is properly created and saved, it is possible to access to its fields as well as getting some information about them.

To do that, it is necessary to use of the following endpoint:

curl -X GET https://api.resourcewatch.org/v1/fields/<dataset-id>

Real example

curl -X GET https://api.resourcewatch.org/v1/fields/1170030b-9725-4bfe-8fb4-1b0eb81020d2

Response

{
    "tableName": "public.cait_2_0_country_ghg_emissions_toplow2011",
    "fields": {
        "cartodb_id": {
            "type": "number"
        },
        "the_geom": {
            "type": "geometry"
        },
        "the_geom_webmercator": {
            "type": "geometry"
        },
        "x": {
            "type": "string"
        },
        "y": {
            "type": "number"
        },
        "z": {
            "type": "string"
        }
    }
}

Rasdaman

The structure of datacubes needs a more verbose field specification. The fields endpoint for rasdaman-backed datasets includes information on the spatial reference system, nodata values, axes, units, and bands. It looks like so:

Example

curl -i  -XGET 'http://api.resourcewatch.org/v1/fields/491ae6fe-6767-44d1-b5c3-c7b8b384bb7a'

Response

{
  "coverageId": "nightlights",
  "srs": {
    "srsDimension": "2",
    "srs": "crs/EPSG/0/4326"
  },
  "axisLabels": "Lat Long",
  "uomLabels": "degree degree",
  "fields": {
    "undefined": {
      "swe:nilValues": {
        "swe:NilValues": {
          "swe:nilValue": [
            {
              "reason": "",
              "$t": "1"
            },
            {
              "reason": "",
              "$t": "2"
            }
          ]
        }
      },
      "swe:uom": {
        "code": "10^0"
      }
    }
  },
  "coverageBounds": {
    "upperCorner": "89.999999999966665 180.000000000189335",
    "lowerCorner": "-89.999999999961335 -179.999999999666665"
  }
}

Metadata

Metadata definition

Metadata can be any kind of data associated to an existing resource (i.e. Dataset, Layer or Widget)

Some fields are important to identify the entity properly; others are just optional and give extra information about it.

Field Description Type
application The metadata application String
language The metadata language String
dataset The associated dataset id to the metadata String
resource The resource associated to the metadata Object
– id Resource id String
– type Resource type String
name The metadata name String
description The metadata description String
source The metadata source String
citation The metadata citation String
license The metadata license type String
info Some info about the metadata Object
units Measurement units Object

Creating a metadata object

Field Required/Optional
application required
language required
dataset required
name optional
description optional
source optional
citation optional
license optional
info optional
units optional

The “application” and “language” attributes are required and it is mandatory to include them in the payload.

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/metadata \
-H "Content-Type: application/json"  -d \
 '{
   "application": <app>,
   "language": <language>
  }'

Real example

curl -X POST https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/metadata \
-H "Content-Type: application/json"  -d \
 '{
   "application": "rw",
   "language": "en"
  }'

Response: 200 OK HTTP RESPONSE + JSON-API-LIKE BODY

{
  "data": [
    {
      "id": "942b3f38-9504-4273-af51-0440170ffc86-dataset-942b3f38-9504-4273-af51-0440170ffc86-rw-en",
      "type": "metadata",
      "attributes": {
        "dataset": "942b3f38-9504-4273-af51-0440170ffc86",
        "application": "rw",
        "resource": {
          "type": "dataset",
          "id": "942b3f38-9504-4273-af51-0440170ffc86"
        },
        "language": "en",
        "createdAt": "2017-01-20T08:07:53.272Z",
        "updatedAt": "2017-01-20T08:07:53.272Z",
        "status": "published"
      }
    }
  ]
}

It could respond with a 401 status code if the request is not authenticated, 403 if the request is not allowed to do that operation, 400 if the request is not well formatted, or 5XX HTTP codes in other cases.

The same operation applies to Widget and Layer just changing the endpoint for the appropriate one.

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/metadata \
-H "Content-Type: application/json"  -d \
 '{
   "application": <app>,
   "language": <language>
  }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/metadata \
-H "Content-Type: application/json"  -d \
 '{
   "application": <app>,
   "language": <language>
  }'

Getting metadata

application filter: application: gfw, gfw-climate, prep, rw, forest-atlas (select one or some of them)

language filter: language: select between available languages (select one or some of them)

limit filter: limit: the desired number

Custom param for /metadata endpoint: type: [dataset, widget, layer]

curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/metadata
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/metadata
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/metadata

Real example

curl -X GET https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/metadata

Updating a metadata

Partial update:

The “application” and “language” attributes are required and it is mandatory to include them in the payload.

curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset-id>/metadata \
-H "Content-Type: application/json"  -d \
 '{
   "application": <app>,
   "language": <language>
  }'

Real example

curl -X PATCH https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/metadata \
-H "Content-Type: application/json"  -d \
 '{
   "application": "rw",
   "language": "en",
   "name": "Cloud Computing Market - USA - 2016",
   "source": "http://www.forbes.com/",
   "info": {
       "summary": "These and many other insights are from the latest series of cloud computing forecasts and market estimates produced by IDC, Gartner, Microsoft and other research consultancies. Amazon’s decision to break out AWS revenues and report them starting in Q1 FY2015 is proving to be a useful benchmark for tracking global cloud growth.  In their latest quarterly results released on January 28, Amazon reported that AWS generated $7.88B in revenues and attained a segment operating income of $1.863B. Please see page 8 of the announcement for AWS financials.  For Q4, AWS achieved a 28.5% operating margin (% of AWS net sales).",
       "author": "Louis Columbus",
       "date": "MAR 13, 2016 @ 10:42 PM",
       "link": "http://www.forbes.com/sites/louiscolumbus/2016/03/13/roundup-of-cloud-computing-forecasts-and-market-estimates-2016/#5875cf0074b0"
   }
  }'

Response

{
  "data": [
    {
      "id": "942b3f38-9504-4273-af51-0440170ffc86-dataset-942b3f38-9504-4273-af51-0440170ffc86-rw-en",
      "type": "metadata",
      "attributes": {
        "dataset": "942b3f38-9504-4273-af51-0440170ffc86",
        "application": "rw",
        "resource": {
          "type": "dataset",
          "id": "942b3f38-9504-4273-af51-0440170ffc86"
        },
        "language": "en",
        "name": "Cloud Computing Market - USA - 2016",
        "source": "http://www.forbes.com/",
        "info": {
          "summary": "These and many other insights are from the latest series of cloud computing forecasts and market estimates produced by IDC, Gartner, Microsoft and other research consultancies. Amazon’s decision to break out AWS revenues and report them starting in Q1 FY2015 is proving to be a useful benchmark for tracking global cloud growth.  In their latest quarterly results released on January 28, Amazon reported that AWS generated $7.88B in revenues and attained a segment operating income of $1.863B. Please see page 8 of the announcement for AWS financials.  For Q4, AWS achieved a 28.5% operating margin (% of AWS net sales).",
          "author": "Louis Columbus",
          "date": "MAR 13, 2016 @ 10:42 PM",
          "link": "http://www.forbes.com/sites/louiscolumbus/2016/03/13/roundup-of-cloud-computing-forecasts-and-market-estimates-2016/#5875cf0074b0"
        },
        "createdAt": "2017-01-20T08:07:53.272Z",
        "updatedAt": "2017-01-20T08:40:30.190Z",
        "status": "published"
      }
    }
  ]
}

Deleting a metadata

The “application” and “language” attributes are required and it is mandatory to include them in the query params.

curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset-id>/metadata?application=<app-id>&language=<language>

Real example

curl -X DELETE https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/metadata?application=rw&language=en \

Getting all

curl -X GET https://api.resourcewatch.org/v1/metadata

Real examples

curl -X GET https://api.resourcewatch.org/v1/metadata
curl -X GET https://api.resourcewatch.org/v1/metadata?type=dataset
curl -X GET https://api.resourcewatch.org/v1/metadata?type=widget
curl -X GET https://api.resourcewatch.org/v1/metadata?application=rw&language=es,en&limit=20
curl -X GET https://api.resourcewatch.org/v1/metadata?application=rw,gfw&language=en&type=dataset
curl -X GET https://api.resourcewatch.org/v1/metadata?language=en

Finding (getting) by ids

The “ids” property is required in the payload, and in other case the endpoint responds with a 400 HTTP ERROR (Bad Request) This property can be an Array or a String (comma-separated) payload -> {“ids”: [“112313”, “111123”]} payload -> {“ids”: “112313, 111123”}

application filter: application: gfw, gfw-climate, prep, rw, forest-atlas (select one or some of them)

language filter: language: select between available languages (select one or some of them)

limit filter: limit: the desired number

Custom param for the metadata endpoint: type: [dataset, widget, layer]

curl -X POST https://api.resourcewatch.org/v1/dataset/metadata/find-by-ids \
-H "Content-Type: application/json"  -d \
 '{
   "ids": [<ids>]
  }'

Real example

curl -X POST https://api.resourcewatch.org/v1/dataset/metadata/find-by-ids \
-H "Content-Type: application/json"  -d \
 '{
     "ids": "b000288d-7037-43ba-aa34-165eab549613, 942b3f38-9504-4273-af51-0440170ffc86"
  }'

Response

{
  "data": [
    {
      "id": "b000288d-7037-43ba-aa34-165eab549613-dataset-b000288d-7037-43ba-aa34-165eab549613-prep-en",
      "type": "metadata",
      "attributes": {
        "dataset": "b000288d-7037-43ba-aa34-165eab549613",
        "application": "prep",
        "resource": {
          "type": "dataset",
          "id": "b000288d-7037-43ba-aa34-165eab549613"
        },
        "language": "en",
        "name": "Projected temperature change",
        "description": "The Puget Sound region is projected to warm rapidly during the 21st century. Prior to mid-century, the projected increase in air temperatures is about the same for all greenhouse gas scenarios, a result of the fact that a certain amount of warming is already “locked in” due to past emissions. After about 2050, projected warming depends on the amount of greenhouse gases emitted globally in the coming decades. For the 2050s (2040-2069, relative to 1970-1999), annual average air temperature is projected to rise +4.2°F to +5.9°F, on average, for a low (RCP 4.5) and a high (RCP 8.5) greenhouse gas scenario. These indicators are derived from the Multivariate Adaptive Constructed Analogs (MACA) CMIP5 Future Climate Dataset from the University of Idaho. For more information about this analysis, please see http://cses.washington.edu/picea/mauger/ps-sok/ps-sok_sec12_builtenvironment_2015.pdf. For more information about the MACA CMIP5 Future Climate Dataset please see http://maca.northwestknowledge.net/index.php",
        "source": "http://maca.northwestknowledge.net",
        "citation": "Abatzoglou, J. T.,   Brown, T. J. 2012. A comparison of statistical downscaling methods suited for wildfire applications. International Journal of Climatology, 32(5), 772-780. doi: http://dx.doi.org/10.1002/joc.2312 ",
        "license": "Public domain",
        "info": {
          "organization": "Joe Casola, University of Washington",
          "license": "Public domain",
          "source": "http://maca.northwestknowledge.net",
          "citation": "Abatzoglou, J. T.,   Brown, T. J. 2012. A comparison of statistical downscaling methods suited for wildfire applications. International Journal of Climatology, 32(5), 772-780. doi: http://dx.doi.org/10.1002/joc.2312 ",
          "description": "The Puget Sound region is projected to warm rapidly during the 21st century. Prior to mid-century, the projected increase in air temperatures is about the same for all greenhouse gas scenarios, a result of the fact that a certain amount of warming is already “locked in” due to past emissions. After about 2050, projected warming depends on the amount of greenhouse gases emitted globally in the coming decades. For the 2050s (2040-2069, relative to 1970-1999), annual average air temperature is projected to rise +4.2°F to +5.9°F, on average, for a low (RCP 4.5) and a high (RCP 8.5) greenhouse gas scenario. These indicators are derived from the Multivariate Adaptive Constructed Analogs (MACA) CMIP5 Future Climate Dataset from the University of Idaho. For more information about this analysis, please see http://cses.washington.edu/picea/mauger/ps-sok/ps-sok_sec12_builtenvironment_2015.pdf. For more information about the MACA CMIP5 Future Climate Dataset please see http://maca.northwestknowledge.net/index.php",
          "short-description": "Projected temperature change in the Puget Sound Lowlands relative to average temperature between 1950-2005. Light colored lines in the background show the range of projections. All climate scenarios project warming for the Puget Sound region during the 21st century.",
          "subtitle": "",
          "title": "Projected temperature change"
        },
        "createdAt": "2016-12-13T10:02:28.337Z",
        "updatedAt": "2016-12-13T10:03:02.445Z",
        "status": "published"
      }
    },
    {
      "id": "942b3f38-9504-4273-af51-0440170ffc86-dataset-942b3f38-9504-4273-af51-0440170ffc86-rw-en",
      "type": "metadata",
      "attributes": {
        "dataset": "942b3f38-9504-4273-af51-0440170ffc86",
        "application": "rw",
        "resource": {
          "type": "dataset",
          "id": "942b3f38-9504-4273-af51-0440170ffc86"
        },
        "language": "en",
        "name": "Cloud Computing Market - USA - 2016",
        "source": "http://www.forbes.com/",
        "info": {
          "link": "http://www.forbes.com/sites/louiscolumbus/2016/03/13/roundup-of-cloud-computing-forecasts-and-market-estimates-2016/#5875cf0074b0",
          "date": "MAR 13, 2016 @ 10:42 PM",
          "author": "Louis Columbus",
          "summary": "These and many other insights are from the latest series of cloud computing forecasts and market estimates produced by IDC, Gartner, Microsoft and other research consultancies. Amazon’s decision to break out AWS revenues and report them starting in Q1 FY2015 is proving to be a useful benchmark for tracking global cloud growth.  In their latest quarterly results released on January 28, Amazon reported that AWS generated $7.88B in revenues and attained a segment operating income of $1.863B. Please see page 8 of the announcement for AWS financials.  For Q4, AWS achieved a 28.5% operating margin (% of AWS net sales)."
        },
        "createdAt": "2017-01-20T08:07:53.272Z",
        "updatedAt": "2017-01-20T08:40:30.190Z",
        "status": "published"
      }
    }
  ]
}

Vocabulary (and Tags)

Tags definition

A way to categorize a resource within a vocabulary context.

Vocabulary definition

The Vocabulary can be described as a cluster of tags.

It is currently possible to just create a Vocabulary without any tags or relationships. To do it, the only parameter that is required is the name of the Vocabulary.

Field Description Type
name The name of the Vocabulary (it has to be unique and it represents the “primaryKey”) String
application The associated application for this vocabulary String

However, the most common use case relies on the relationships creation.

Relationships

This section describes how to associate an existing or new Vocabulary to a resource.

Some important points:

Assign a Vocabulary to an existing Resource

To create a relationship between a resource and a Vocabulary (even if the vocabulary doesn’t exist yet) it is only required that you set the tags that define the relationship.

Some writing operations can take a little more time than reading ones. Even if the relationships are not strong, the writing operations have to ensure consistency along entities.

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/vocabulary/<vocabulary-id> \
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": [<tags>]
  }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/vocabulary/<vocabulary-id> \
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": [<tags>]
  }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/vocabulary/<vocabulary-id> \
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": [<tags>]
  }'

real example

curl -X POST https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/vocabulary/science
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": ["biology", "chemistry"]
  }'

real Response

{
  "data": [
    {
      "id": "vocabularyNameOne",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "tag1",
          "tag2",
          "tag3"
        ]
      }
    },
    {
      "id": "science",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "biology",
          "chemistry"
        ]
      }
    },
    {
      "id": "aaa",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "biology",
          "chemistry"
        ]
      }
    }
  ]
}

Updating Tags of an existing relationship

If a relationship has to be updated, it’s necessary to define it’s new tags. The previous tags will be deleted in benefit of the new ones.

curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset-id>/vocabulary/<vocabulary-id> \
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": [<tags>]
  }'
curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/vocabulary/<vocabulary-id> \
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": [<tags>]
  }'
curl -X PATCH https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/vocabulary/<vocabulary-id> \
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": [<tags>]
  }'

real example

curl -X PATCH https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/vocabulary/science
-H "Content-Type: application/json"  -d \
 '{
 "application": <application>,
   "tags": ["maths", "astronomy"]
  }'

response

{
  "data": [
    {
      "id": "vocabularyNameOne",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "tag1",
          "tag2",
          "tag3"
        ]
      }
    },
    {
      "id": "science",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "maths",
          "astronomy"
        ]
      }
    },
    {
      "id": "aaa",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "biology",
          "chemistry"
        ]
      }
    }
  ]
}

Creating several relationships

There is also an endpoint that allows you to create some relationships in the same request.

curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/vocabulary \
-H "Content-Type: application/json"  -d \
 '{
   "vocabularyOne": {
   "application": <application>,
       "tags": [<tags>]
   },
   "vocabularyTwo": {
   "application": <application>,
       "tags": [<tags>]
   }
  }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/vocabulary\
-H "Content-Type: application/json"  -d \
'{
  "vocabularyOne": {
  "application": <application>,
      "tags": [<tags>]
  },
  "vocabularyTwo": {
  "application": <application>,
      "tags": [<tags>]
  }
 }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/vocabulary \
-H "Content-Type: application/json"  -d \
'{
  "vocabularyOne": {
  "application": <application>,
      "tags": [<tags>]
  },
  "vocabularyTwo": {
  "application": <application>,
      "tags": [<tags>]
  }
 }'

real example

curl -X POST https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/vocabulary?application=<application>
-H "Content-Type: application/json"  -d \
 '{
     "country": {
         "tags": ["Spain", "Italy", "Portugal"]
     },
     "sport": {
         "tags": ["football", "basketball", "voleyball"]
     },
     "color": {
         "tags": ["red", "green", "blue"]
     }
  }'

response

{
  "data": [
    {
      "id": "vocabularyNameTwo",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "tag1",
          "tag2",
          "tag3"
        ]
      }
    },
    {
      "id": "vocabularyNameOne",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "tag1",
          "tag2",
          "tag3"
        ]
      }
    },
    {
      "id": "a",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "tag1",
          "tag2",
          "tag3"
        ]
      }
    },
    {
      "id": "b",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "tag1",
          "tag2",
          "tag3"
        ]
      }
    },
    {
      "id": "newV",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "test1",
          "test2"
        ]
      }
    },
    {
      "id": "country",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "Spain",
          "Italy",
          "Portugal"
        ]
      }
    },
    {
      "id": "sport",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "football",
          "basketball",
          "voleyball"
        ]
      }
    },
    {
      "id": "color",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "red",
          "green",
          "blue"
        ]
      }
    }
  ]
}

Deleting relationships

curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset-id>/vocabulary/<vocabulary-id>
curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/vocabulary/<vocabulary-id>
curl -X DELETE https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/vocabulary/<vocabulary-id>

real example

curl -X DELETE https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/vocabulary/science

response

{
  "data": [
    {
      "id": "country",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "Spain",
          "Italy",
          "Portugal"
        ]
      }
    },
    {
      "id": "color",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "red",
          "green",
          "blue"
        ]
      }
    }
  ]
}

Getting vocabularies associated to a resource

You can be request all vocabularies that are associated to a particular resource.

curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/vocabulary
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/vocabulary
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/vocabulary

real example

curl -X GET https://api.resourcewatch.org/v1/dataset/942b3f38-9504-4273-af51-0440170ffc86/vocabulary

response

{
  "data": [
    {
      "id": "country",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "Spain",
          "Italy",
          "Portugal"
        ]
      }
    },
    {
      "id": "color",
      "type": "vocabulary",
      "attributes": {
        "tags": [
          "red",
          "green",
          "blue"
        ]
      }
    }
  ]
}

Getting a single relationship (broken now)

curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/vocabulary/<vocabulary-id>
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/<widget-id>/vocabulary/<vocabulary-id>
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/<layer-id>/vocabulary/<vocabulary-id>

Getting resources (COMMON USE CASE)

There is also an endpoint available which accepts requests just indicating resource type and the desired vocabulary-tag matching.

It currently supports DOUBLE-OR pattern matching, meaning the API will return all resources that at least have one (or more) tags in a particular vocabulary. At the same time it will also apply an OR to the entities of other vocabulary-tag matchings.

The query has to be set in the url by the query params.

curl -X GET https://api.resourcewatch.org/v1/dataset/vocabulary/find
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/vocabulary/find
curl -X GET https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/vocabulary/find

real example

curl -X GET http://api.resourcewatch.org/v1/dataset/vocabulary/find?legacy=cdi,coasts

Getting all vocabularies

This endpoint is quite useful to have a quick overview of all existing vocabularies and resources.

curl -X GET https://api.resourcewatch.org/v1/vocabulary

Finding (getting) by ids

The “ids” property is required in the payload. In other cases the endpoint responds with a 400 HTTP ERROR (Bad Request) This property can be an Array or a String (comma-separated) payload -> {“ids”: [“112313”, “111123”]} payload -> {“ids”: “112313, 111123”}

curl -X POST https://api.resourcewatch.org/v1/dataset/vocabulary/find-by-ids \
-H "Content-Type: application/json"  -d \
 '{
   "ids": [<ids>]
  }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/widget/vocabulary/find-by-ids \
-H "Content-Type: application/json"  -d \
 '{
   "ids": [<ids>]
  }'
curl -X POST https://api.resourcewatch.org/v1/dataset/<dataset-id>/layer/vocabulary/find-by-ids \
-H "Content-Type: application/json"  -d \
 '{
   "ids": [<ids>]
  }'

real example

curl -X POST https://api.resourcewatch.org/v1/dataset/vocabulary/find-by-ids \
-H "Content-Type: application/json"  -d \
 '{
    "ids": "942b3f38-9504-4273-af51-0440170ffc86, 08ff8183-48dc-457a-8924-bb4e7a87b8a8"
  }'

response

{
  "data": [
    {
      "type": "resource",
      "id": "08ff8183-48dc-457a-8924-bb4e7a87b8a8",
      "attributes": {
        "legacy": [
          "cdi",
          "inundation",
          "national",
          "united states",
          "local",
          "coasts",
          "flooding",
          "health"
        ]
      }
    },
    {
      "type": "resource",
      "id": "942b3f38-9504-4273-af51-0440170ffc86",
      "attributes": {
        "country": [
          "Spain",
          "Italy",
          "Portugal"
        ],
        "color": [
          "red",
          "green",
          "blue"
        ]
      }
    }
  ]
}

Vocabulary Creation

As was mentioned before, it is possible to just create a new and empty vocabulary

curl -X POST https://api.resourcewatch.org/v1/vocabulary/vocabularyName \
-H "Content-Type: application/json"  -d \
 '{
   "application": <application>,
   "name": <vocabularyName>
  }'

It is also possible to update and delete an entire vocabulary. Said that, because it’s necessary to keep consistency between entities with weak relationship, these operations are only available to SUPERADMINS.

Geostore

What is Geostore?

Geostore is a geojson database. You can save your geojson or obtain geojson by country, region, Protected areas, etc.

Geostore object contains the following fields:

Field Description Type
id Id of the geostore Text
geojson Geojson with the geometry Object
hash MD5 hash generated from geojson. Is the same that the id Object
provider This field should be completed if the geostore was created from a provider Object
– type Provider type Text
– table Table name Text
– user User of the account Text
– filter Conditions to obtain the geojson. It is possible use AND & OR conditions. This conditions must only return one row. Text
areaHa Area in Hectares of the geojson Number
bbox Bounding box of the geojson Array

Create Geostore

You can create a geostore in 4 different ways:

With a Geojson

If you have your own geojson, you can save it in geostore. To create the geostore, you need to define all the required fields in the request body. The fields that compose a geostore are:

Field Description Type Values Required
geojson Geojson with your geometry Object Yes

To create a Geostore, you have to do a POST query with the following body:

curl -X POST https://api.resourcewatch.org/v1/geostore \
-H "Content-Type: application/json"  -d \
 '{
   "geojson": <yourGeoJSONObject>
  }'

Real example

curl -X POST https://api.resourcewatch.org/v1/geostore \
-H "Content-Type: application/json"  -d \
 '{
   "geojson":{
      "type":"FeatureCollection",
      "features":[
         {
            "type":"Feature",
            "properties":{

            },
            "geometry":{
               "type":"LineString",
               "coordinates":[
                  [
                     -3.9942169189453125,
                     41.044922165782175
                  ],
                  [
                     -3.995418548583985,
                     41.03767166215326
                  ],
                  [
                     -3.9842605590820312,
                     41.03844854003296
                  ],
                  [
                     -3.9844322204589844,
                     41.04589315472392
                  ],
                  [
                     -3.9942169189453125,
                     41.044922165782175
                  ]
               ]
            }
         },
         {
            "type":"Feature",
            "properties":{

            },
            "geometry":{
               "type":"Polygon",
               "coordinates":[
                  [
                     [
                        -4.4549560546875,
                        40.84706035607122
                     ],
                     [
                        -4.4549560546875,
                        41.30257109430557
                     ],
                     [
                        -3.5211181640624996,
                        41.30257109430557
                     ],
                     [
                        -3.5211181640624996,
                        40.84706035607122
                     ],
                     [
                        -4.4549560546875,
                        40.84706035607122
                     ]
                  ]
               ]
            }
         }
      ]
   }
}'

The response will be 200 if the geostore saves correctly and returns the geostore object with all information:

Example response

{
   "data":{
      "type":"geoStore",
      "id":"c9bacccfb9c3fe225dc67545bb93a5cb",
      "attributes":{
         "geojson":{
            "features":[
               {
                  "type":"Feature",
                  "geometry":{
                     "type":"Polygon",
                     "coordinates":[
                        [
                           [
                              -4.4549560546875,
                              40.84706035607122
                           ],
                           [
                              -4.4549560546875,
                              41.30257109430557
                           ],
                           [
                              -3.5211181640624996,
                              41.30257109430557
                           ],
                           [
                              -3.5211181640624996,
                              40.84706035607122
                           ],
                           [
                              -4.4549560546875,
                              40.84706035607122
                           ]
                        ]
                     ]
                  }
               }
            ],
            "crs":{

            },
            "type":"FeatureCollection"
         },
         "hash":"c9bacccfb9c3fe225dc67545bb93a5cb",
         "provider":{

         },
         "areaHa":397372.34122605197,
         "bbox":[
            -4.4549560546875,
            40.84706035607122,
            -3.5211181640624996,
            41.30257109430557
         ]
      }
   }
}

From country

If you need obtain the geostore of a country, you can obtain it with the ISO3 code in the Geostore API.

GET https://api.resourcewatch.org/v1/geostore/admin/<ISO3>

curl -X GET https://api.resourcewatch.org/v1/geostore/admin/<ISO3>

Real example obtaining the geostore of Spain shell curl -X GET https://api.resourcewatch.org/v1/geostore/admin/ESP

Country list

A list of countries can be obtained from this endpoint.

curl -X GET https://api.resourcewatch.org/v1/geostore/admin/list

Example response

{
    "data": [{
        "geostoreId": "35a6d982388ee5c4e141c2bceac3fb72",
        "iso": "ESP",
        "name": "Spain"
    }, {
        "geostoreId": "8f77fe62cf15d5098ba0ee11c5126aa6",
        "iso": "FRA",
        "name": "France"
    }, {
        "geostoreId": "1d568c183033da6c17cc28c4aecf1bcf",
        "iso": "cod",
        "name": "Democratic Republic of the Congo"
    }]
}

From country and region

If you need obtain the geostore of a region in a country, you can obtain it with the ISO3 and region code:

GET https://api.resourcewatch.org/v1/geostore/admin/<ISO3>/<regionCode>

curl -X GET https://api.resourcewatch.org/v1/geostore/admin/<ISO3>/<regionCode>

Real example obtaining the geostore of Madrid’s Comunity in Spain

curl -X GET https://api.resourcewatch.org/v1/geostore/admin/ESP/8

From World Database on Protected Areas (wdpa)

Is possible obtain the geostore of a World Database on Protected Areas of the world. You only need the id of the protected area (WDPA). World Database on Protected Areas web

GET https://api.resourcewatch.org/v1/geostore/wdpa/<wdpaId>

curl -X GET https://api.resourcewatch.org/v1/geostore/wdpa/<wdpaId>

Real example obtaining the geostore of ‘Sierra de Guadarrama’ protected area

curl -X GET https://api.resourcewatch.org/v1/geostore/wdpa/555538160

From land use areas

Geostore has the geojson of 4 differents lands use:

Oil palm

GET https://api.resourcewatch.org/v1/geostore/use/oilpalm/<id>

curl -X GET https://api.resourcewatch.org/v1/geostore/use/oilpalm/<id>

Real example obtaining the geostore of one Oil palm area

curl -X GET https://api.resourcewatch.org/v1/geostore/use/oilpalm/556

Mining

GET https://api.resourcewatch.org/v1/geostore/use/mining/<id>

curl -X GET https://api.resourcewatch.org/v1/geostore/use/mining/<id>

Real example obtaining the geostore of one mining area

curl -X GET https://api.resourcewatch.org/v1/geostore/use/mining/573

Wood fiber

GET https://api.resourcewatch.org/v1/geostore/use/fiber/<id>

curl -X GET https://api.resourcewatch.org/v1/geostore/use/fiber/<id>

Real example obtaining the geostore of one Wood fiber area

curl -X GET https://api.resourcewatch.org/v1/geostore/use/fiber/346

Congo Basin logging roads

GET https://api.resourcewatch.org/v1/geostore/use/logging/<id>

curl -X GET https://api.resourcewatch.org/v1/geostore/use/logging/<id>

Real example obtaining the geostore of Oil palm area

curl -X GET https://api.resourcewatch.org/v1/geostore/use/logging/102

From Carto

If your geojson is in carto table, is possible import this geojson in geostore. To import the geojson in geostore, you need to define all of the required fields in the request body. The fields that compose a import are:

Field Description Type Values Required
provider Provider of data Object Yes
– type Provider type Text carto Yes
– table Table name Text Yes
– user User of the account Text Yes
– filter Conditions to obtain the geojson. Is possible put and and or conditions. This conditions must only return one row. Text Yes

To import a Geostore, you have to do a POST with the following body:

curl -X POST https://api.resourcewatch.org/v1/geostore \
-H "Content-Type: application/json"  -d \
 '{
    "provider":{
        "type": "carto",
        "table": <tableName>,
        "user": <userName>,
        "filter": <conditions>
    }
}'

Real example

curl -X POST https://api.resourcewatch.org/v1/geostore \
-H "Content-Type: application/json"  -d \
 '{
    "provider":{
        "type": "carto",
        "table": "gfw_mining",
        "user": "wri-01",
        "filter": "cartodb_id=573"
    }
}'

Example response

{
  "data": {
    "type": "geoStore",
    "id": "26f8975c4c647c19a2edaa11f23880a2",
    "attributes": {
      "geojson": {
        "features": [
          {
            "type": "Feature",
            "geometry": {
              "type": "MultiPolygon",
              "coordinates": [
                [
                  [
                    [
                      -74.0957370284411,
                      10.6814701233475
                    ],
                    [
                      -74.0957357154309,
                      10.654348341203
                    ],
                    [
                      -74.1100850695703,
                      10.6543473339623
                    ],
                    [
                      -74.1100876551212,
                      10.6814691125096
                    ],
                    [
                      -74.0957370284411,
                      10.6814701233475
                    ]
                  ]
                ]
              ]
            }
          }
        ],
        "crs": {},
        "type": "FeatureCollection"
      },
      "hash": "26f8975c4c647c19a2edaa11f23880a2",
      "provider": {
        "filter": "cartodb_id=573",
        "user": "wri-01",
        "table": "gfw_mining",
        "type": "carto"
      },
      "areaHa": 471.001953054716,
      "bbox": [
        -74.1100876551212,
        10.6543473339623,
        -74.0957357154309,
        10.6814701233475
      ]
    }
  }
}

Obtain a Geostore

To obtain a geostore, you only need the id of the Geostore. You can perform a GET request for the geostore with its id.

curl -X GET https://api.resourcewatch.org/v1/geostore/<geostoreId>

Real example obtaining one geostore

curl -X GET https://api.resourcewatch.org/v1/geostore/use/logging/26f8975c4c647c19a2edaa11f23880a2

Example response

{
  "data": {
    "type": "geoStore",
    "id": "26f8975c4c647c19a2edaa11f23880a2",
    "attributes": {
      "geojson": {
        "features": [
          {
            "type": "Feature",
            "geometry": {
              "type": "MultiPolygon",
              "coordinates": [
                [
                  [
                    [
                      -74.0957370284411,
                      10.6814701233475
                    ],
                    [
                      -74.0957357154309,
                      10.654348341203
                    ],
                    [
                      -74.1100850695703,
                      10.6543473339623
                    ],
                    [
                      -74.1100876551212,
                      10.6814691125096
                    ],
                    [
                      -74.0957370284411,
                      10.6814701233475
                    ]
                  ]
                ]
              ]
            }
          }
        ],
        "crs": {},
        "type": "FeatureCollection"
      },
      "hash": "26f8975c4c647c19a2edaa11f23880a2",
      "provider": {
        "filter": "cartodb_id=573",
        "user": "wri-01",
        "table": "gfw_mining",
        "type": "carto"
      },
      "areaHa": 471.001953054716,
      "bbox": [
        -74.1100876551212,
        10.6543473339623,
        -74.0957357154309,
        10.6814701233475
      ]
    }
  }
}

Subscriptions

Subscription represents to wich datasets and analyisis a user can have access to.

Subscribable datasets

In order to create a subscription, a dataset must be prepared to accept them. This is achieved by declaring some queries in the dataset json object sent to the /v1/dataset endpoint under the subscribableproperty.

{
    "name": "dataset name",
    "application": ["app"],
    "provider": "dataset provider",
    "other": "dataset_fields",
    "subscribable": {
        "test_subscription": {
            "dataQuery": "SELECT * FROM dataset-name  WHERE \"reported_date\" >= '{{begin}}' AND \"reported_date\" <= '{{end}}' AND \"number_dead\" > 0 ORDER BY reported_date DESC LIMIT 10",
            "subscriptionQuery": "SELECT COUNT(*) FROM dataset-name WHERE \"reported_date\" >= '{begin}' AND \"reported_date\" <= '{end}' AND \"number\" > 0"
        }
    }
}

Inside the subscribable object, one (or several) subobjects can be declared. In the provided example, the test_subscription is provided, with both a dataQuery and a subscriptionQuery. The former will be evaluated as the subscription’s content, while the latter will be evaluated to check if a subscription has changed since the last update. Both queries can contain two special keywords: {begin} and {end}. These will be substituted with ansi-formatted datetimes –with the datetime in which the subscription was last evaluated, and the datetime at the time of evaluation, respectively.

Create Subscription

Field Description Type
name Name Text
application Application of the subscription gfw, rw, prep
language Language of the subscriptions (used to select the email template) en, es, fr, pt, zh
resource This field contains the subscription is of type email or hook Object
– type Type EMAIL or URL
– content Email or url Text
datasets Array of datasets of the subscription Array
datasetsQuery Subscriptions to subscribable datasets Array
– id Id of dataset ObjectId
– type Type of subscription defined in the dataset Text
– params Geographic area of the subscription Object

You only require one of datasets or datasetsQuery, but not both.

A way to determine the area of interest for the subscriptions needs to be provided. A subscription can be created in six different ways:

With an area

Field Description Type
params Geographic area of the subscription Object
– area Id of area object Text (ObjectId)

To create a Subscription, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
    "name": "<name>",
    "datasets": [
        "<dataset>"
    ],
    "params": {
        "geostore": "35a6d982388ee5c4e141c2bceac3fb72"
    },
    "datasetsQuery": [
        {
            "id": ":subscription_dataset_id",
            "type": "test_subscription",
            "threshold": 1
        }
    ],
    "application": "rw",
    "language": "en",
    "resource": {
        "type": "EMAIL",
        "content": "email@addres.com"
    }
}'

In this case, a subscription is being created in reference to the subscribable field present in the previously defined dataset. After confirming the subscription the subscriptionQuery will be ran and its result will be compared against the threshold. If the query result is at least equal to the threshold, a new alert will be sent to the subscription’s email.

From country

Field Description Type
params Geographic area of the subscription Object
– iso Country or region information Object
—- country Iso code Text

To create a Subscription, you have to do a POST with the following body:

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "iso": {
           "country": "<iso>"
       }
   },
   "datasetsQuery": [{}]
  }'

From country and region

Field Description Type
params Geographic area of the subscription Object
– iso Country or region information Object
—- country Iso code Text
—- region Region code Number

To create a Subscription, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "iso": {
           "country": "<iso>",
           "region": "<region>"
       }
    }
  }'

From World Database on Protected Areas (wdpa)

Field Description Type
params Geographic area of the subscription Object
– wdpaid id of protected area Number

To create a Subscription, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "wdpaid": <idWdpa>
    },
   "datasetsQuery": [{}]
  }'

From land use areas

Field Description Type
params Geographic area of the subscription Object
– use Use name Text
– useid Id use Number

To create a Subscription, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "use": "<useName>",
       "useid": <id>
    },
   "datasetsQuery": [{}]
  }'

Subscription has 4 different lands uses:

Oil palm

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "use": "oilpalm",
       "useid": <id>
    },
    "datasetsQuery": [{}]
  }'

Mining

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "use": "mining",
       "useid": <id>
    }
  }'

Wood fiber

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "use": "fiber",
       "useid": <id>
    },
    "datasetsQuery": [{}]
  }'

Congo Basin logging roads

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "use": "logging",
       "useid": <id>
    },
    "datasetsQuery": [{}]
  }'

From geostore

Field Description Type
params Geographic area of the subscription Object
– geostore Id of geostore Text

To create a Subscription, you have to do a POST request with the following body:

curl -X POST https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "application": "<application>",
   "language": "<language>",
   "resource": {
       "type": "<type>",
       "content": "<content>"
   },
   "datasets" : ["<dataset>"],
   "params": {
       "geostore": "<idGeostore>"
    },  
   "datasetsQuery": [{}]
  }'

Confirm subscription

All subscriptions are created unconfirmed. The user needs confirm his subscription with this endpoint.

curl -X GET https://api.resourcewatch.org/v1/subscriptions/:id/confirm

Obtain the subscriptions for a user

To get the authenticated user subscriptions:

curl -X GET https://api.resourcewatch.org/v1/subscriptions \
-H "Authorization: Bearer <your-token>"

Response:


{
   "data":[
      {
         "type":"subscription",
         "id":"587cc014f3b3f6280058e478",
         "attributes":{
            "name":"test",
            "createdAt":"2017-01-16T12:45:08.434Z",
            "userId":"57a063da096c4eda523e99ae",
            "resource":{
               "type":"EMAIL",
               "content":"pepe@gmail.com"
            },
            "datasets":[
               "viirs-active-fires"
            ],
            "params":{
               "iso":{
                  "region":null,
                  "country":null
               },
               "wdpaid":null,
               "use":null,
               "useid":null,
               "geostore":"50601ff9257df221e808af427cb47701"
            },
            "confirmed":false,
            "language":"en",
            "datasetsQuery":[

            ]
         }
      }
   ]
}

Resend confirmation

To resend the confirmation:

curl -X PATCH https://api.resourcewatch.org/v1/subscriptions/:id/send_confirmation \
-H "Authorization: Bearer <your-token>"

Modify subscription

To modify a subscription:

curl -X PATCH https://api.resourcewatch.org/v1/subscriptions/:id \
-H "Authorization: Bearer <your-token>"

With a body with the same format as before.

Unsubscribe

To unsubscribe from a subscription:

curl -X GET https://api.resourcewatch.org/v1/subscriptions/:id/unsubscribe \
-H "Authorization: Bearer <your-token>"

Delete subscription

To unsubscribe (delete a subscription):

curl -X DELETE https://api.resourcewatch.org/v1/subscriptions/:id/unsubscribe \
-H "Authorization: Bearer <your-token>"

Favorites

The users can save their own favorites resources of the API.

Field Description Type
id Name Text
resourceId Id of the resource Text
resourceType Type of resource Text (dataset, layer, widget)
userId Id of the owner user Text
createdAt Creation date Date

Create Favorite

To create a favorite, you need to define all next fields in the request body. The required fields that compose a favorite are:

Field Description Type
resourceId Id of the resource Text
resourceType Type of resource Text (dataset, layer, widget)

To create a favorite, you have to do a POST with the following body:

curl -X POST https://api.resourcewatch.org/v1/favourite \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "resourceType":"<resourceType>",
   "resourceId": "<resourceId>"
  }'

Get favorites

This endpoint returns the favorites of the logged user.

To get all favorite of the logged user, you have to do a GET request:

curl -X GET https://api.resourcewatch.org/v1/favourite \
-H "Authorization: Bearer <your-token>"

You can also retrieve all data about the resources by including the query parameter “include=true” in the request.

curl -X GET https://api.resourcewatch.org/v1/favourite?include=true \
-H "Authorization: Bearer <your-token>"

Get favorite by id

This endpoint returns the favorite with id of the param. If the favorite belongs to other user or not exist, the endpoint returns 400.

To get the favorite by id, you have to do a GET request:

curl -X GET https://api.resourcewatch.org/v1/favourite/:id \
-H "Authorization: Bearer <your-token>"

Delete favorite

This endpoint deletes the favorite with id of the param. If the favorite belongs to other user or not exist, the endpoint returns 400.

To delete the favorite by id, you have to do a DELETE request:

curl -X DELETE https://api.resourcewatch.org/v1/favourite/:id \
-H "Authorization: Bearer <your-token>"

Collections

The users can save a collection of resources in the API.

Field Description Type
name Name of collection owner Text
ownerId Id of the owner Text
resources Resources in the collection Array of Objects
— type The type of resource Text (dataset, layer, widget)
— id The id of the reource Text

Create Collection

To create a collection, you need to define all next fields in the request body. The required fields that compose a collection are:

Field Description Type
name Name of collection owner Text
ownerId The id of the owner Text

To create an empty collection, you have to do a POST with the following body:

curl -X POST https://api.resourcewatch.org/v1/collection \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "ownerId": "<ownerId>"
  }'

You can also add a resource in the body of the request when creating a new collection with the following body:

curl -X POST https://api.resourcewatch.org/v1/collection \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "<name>",
   "ownerId": "<ownerId>",
   "resources": [
     {
      "type": "<type>",
      "id": "<id>"
      }
   ]
  }'

Add Resource to Collection

To create a collection, you need to define all next fields in the request body. The required fields that compose a collection are:

Field Description Type
type Type of resource being added Text (dataset, layer, widget)
id Id of the resource Text

To add a resource to a collection, you have to do a POST with the following body:

curl -X POST https://api.resourcewatch.org/v1/collection/:id/resource \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "type": "<type>",
   "id": "<id>"
  }'

Get Collections

This endpoint returns the collections of the logged user.

To get all collections of the logged user, you have to do a GET request:

curl -X GET https://api.resourcewatch.org/v1/collection \
-H "Authorization: Bearer <your-token>"

Get Collection by id

This endpoint returns the collection with id of the param. If the collection belongs to other user or not exist, the endpoint returns 400.

To get the collection by id, you have to do a GET request:

curl -X GET https://api.resourcewatch.org/v1/collection/:id \
-H "Authorization: Bearer <your-token>"

Delete Collection

This endpoint deletes the collection with id of the param. If the collection belongs to other user or not exist, the endpoint returns 400.

To delete the collection by id, you have to do a DELETE request:

curl -X DELETE https://api.resourcewatch.org/v1/collection/:id \
-H "Authorization: Bearer <your-token>"

Delete Collection Resource

Using this endpoint you can also delete a resource in a collection with the id, resource type and resource id of the param. If the collection belongs to other user or not exist, the endpoint returns 400.

To delete the resource you have to do a DELETE request:

curl -X DELETE https://api.resourcewatch.org/v1/collection/:id/resource/:resourceType/:resourceId \
-H "Authorization: Bearer <your-token>"

Graph

The following graph endpoints are available

List concepts

Returns a list including all the concepts present in the graph

curl -X GET https://api.resourcewatch.org/v1/graph/query/list-concepts

Query example

{
  "data": [
    {
      "id": "europe",
      "label": "Europe",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ],
      "numberOfDatasetsTagged": 0
    },
    {
      "id": "damage",
      "label": "Damage",
      "synonyms": [
        "destruction"
      ],
      "labels": [
        "CONCEPT",
        "TOPIC"
      ],
      "numberOfDatasetsTagged": 2
    },
    {
      "id": "guernsey",
      "label": "Guernsey",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ],
      "numberOfDatasetsTagged": 0
    }
  ]
}

Get inferred concepts

This endpoint returns the set of concepts that are inferred from the set passed as a parameter

Parameters

Parameter Description Type Values Required
concepts List of concepts Text Any Text, values separated by commas Yes
curl -X GET https://api.resourcewatch.org/v1/graph/query/concepts-inferred?concepts=<concept_list>

Example

Concepts inferred from the set: [‘spain’, 'raster’]

https://api.resourcewatch.org/v1/graph/query/concepts-inferred?concepts=spain,raster
{
  "data": [
    {
      "id": "location",
      "label": "Location",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "TOPIC"
      ]
    },
    {
      "id": "eu",
      "label": "EU",
      "synonyms": [
        "European Union"
      ],
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "raster",
      "label": "Raster",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "DATA_TYPE"
      ]
    },
    {
      "id": "oecd",
      "label": "OECD",
      "synonyms": [
        "Organisation for Economic Co-operation and Development"
      ],
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "schengen_area",
      "label": "Schengen Area",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "country",
      "label": "Country",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "continent",
      "label": "Continent",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "global",
      "label": "Global",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "general",
      "label": "General",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "TOPIC"
      ]
    },
    {
      "id": "spain",
      "label": "Spain",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    },
    {
      "id": "dataset",
      "label": "Dataset",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "DATA_TYPE"
      ]
    },
    {
      "id": "europe",
      "label": "Europe",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "GEOGRAPHY"
      ]
    }
  ]
}

Concepts’ ancestors

This endpoint returns the ancestors from the list of concepts provided

Parameters

Parameter Description Type Values Required
concepts List of concepts Text Any Text, values separated by commas Yes
https://api.resourcewatch.org/v1/graph/query/concepts-ancestors?concepts=<concept_list>

Example

Ancestors of the concepts from the set: ['forest_cover’, 'landslide’]

https://api.resourcewatch.org/v1/graph/query/concepts-ancestors?concepts=forest_cover,landslide
{
  "data": [
    {
      "id": "indicator",
      "label": "Indicator",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "TOPIC"
      ]
    },
    {
      "id": "forest",
      "label": "Forest",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "TOPIC"
      ]
    },
    {
      "id": "natural_disaster",
      "label": "Natural disaster",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "TOPIC"
      ]
    },
    {
      "id": "natural_phenomena",
      "label": "Natural phenomena",
      "synonyms": "",
      "labels": [
        "CONCEPT",
        "TOPIC"
      ]
    }
  ]
}

Similar datasets

Returns a set of datasets that are similar to the dataset provider sorted by their degree of similarity.

curl -X GET https://api.resourcewatch.org/v1/graph/query/similar-dataset/<dataset-id>

Parameters available

Parameter Description Type Values Required
published Include only published datasets Boolean true/false No
app List of applications datasets should belong to (at least one of them) Text Any text, values separated by commas No
env Include only datasets with at least one of the specified environments Text One or more values from ['production’, 'preproduction’] No
limit Maximum number of datasets returned by the endpoint Integer A positive integer (3 by default) No

Example

Datasets that are similar to the dataset with id 63a7a997-695d-4629-b6e9-9b169f5c69b including only those that are published with a limit of 6 results in total, datasets from both production and preproduction environments are included.

https://api.resourcewatch.org/v1/graph/query/similar-dataset/63a7a997-695d-4629-b6e9-9b169f5c69bf?published=true&env=production,preproduction&app=rw&limit=6
{
  "data": [
    {
      "dataset": "0a59f415-ee0b-4d19-96f7-c7304c152e1b",
      "concepts": [
        "global",
        "raster",
        "geospatial"
      ]
    },
    {
      "dataset": "0087944f-871c-44bc-b4d9-cd5acfc27023",
      "concepts": [
        "global",
        "raster",
        "geospatial"
      ]
    },
    {
      "dataset": "0303127a-70b0-4164-9251-d8162615d058",
      "concepts": [
        "raster",
        "geospatial"
      ]
    },
    {
      "dataset": "05b7c688-09ba-4f33-90ea-185a1039df43",
      "concepts": [
        "global",
        "geospatial"
      ]
    },
    {
      "dataset": "050f4146-566c-4a6d-9aaa-b49ab66a3090",
      "concepts": [
        "global",
        "geospatial"
      ]
    },
    {
      "dataset": "00abb46f-34e2-4bf7-be30-1fb0b1de022f",
      "concepts": [
        "global",
        "geospatial"
      ]
    }
  ]
}

Similar datasets including ancestors

Returns a set of datasets that are similar to the dataset provider sorted by their degree of similarity as well as taking into account ancestor concepts.

curl -X GET https://api.resourcewatch.org/v1/graph/query/similar-dataset-including-descendent/<dataset-id>

Parameters available

Parameter Description Type Values Required
published Include only published datasets Boolean true/false No
app List of applications datasets should belong to (at least one of them) Text Any text, values separated by commas No
env Include only datasets with at least one of the specified environments Text One or more values from ['production’, 'preproduction’] No
limit Maximum number of datasets returned by the endpoint Integer A positive integer (3 by default) No

Example

Datasets that are similar to the dataset with id 03bfb30e-829f-4299-bab9-b2be1b66b5d4 including only those that are published with a limit of 6 results in total, datasets from both production and preproduction environments are included.

https://api.resourcewatch.org/v1/graph/query/similar-dataset-including-descendent/03bfb30e-829f-4299-bab9-b2be1b66b5d4?published=true&env=production,preproduction&app=rw&limit=6
{
  "data": [
    {
      "dataset": "05b7c688-09ba-4f33-90ea-185a1039df43",
      "concepts": [
        "country",
        "forest",
        "geospatial",
        "table"
      ],
      "numberOfOcurrences": 1
    },
    {
      "dataset": "0448c79d-0ee0-42ff-9331-aeee70cef301",
      "concepts": [
        "forest_cover",
        "forest_gain",
        "forest_loss",
        "geospatial"
      ],
      "numberOfOcurrences": 1
    },
    {
      "dataset": "098b33df-6871-4e53-a5ff-b56a7d989f9a",
      "concepts": [
        "country",
        "geospatial"
      ],
      "numberOfOcurrences": 1
    },
    {
      "dataset": "0be2ce12-79b3-434b-b557-d6ea92d787fe",
      "concepts": [
        "geospatial",
        "table"
      ],
      "numberOfOcurrences": 1
    },
    {
      "dataset": "050f4146-566c-4a6d-9aaa-b49ab66a3090",
      "concepts": [
        "geospatial",
        "table"
      ],
      "numberOfOcurrences": 1
    },
    {
      "dataset": "00abb46f-34e2-4bf7-be30-1fb0b1de022f",
      "concepts": [
        "geospatial",
        "table"
      ],
      "numberOfOcurrences": 1
    }
  ]
}

Search datasets by concepts

This endpoint performs a dataset search based on the concepts provided and the tags that have been associated to all the different datasets that are part of the application. Ancestors of the tags directly associated to a datasets are taken into account in the search.

curl -X GET https://api.resourcewatch.org/v1/graph/query/search-datasets?concepts[0][0]='water'

Up to three sets of concepts can be provided as shown in the example below. Given the following sets of concepts:

The url should be formed as follows:

https://api.resourcewatch.org/v1/graph/query/search-datasets?concepts[0][0]=spain,concepts[0][1]=europe,concepts[1][0]=water,concepts[2][0]=raster,concepts[2][1]=geospatial

AND logical operators are applied among the sets while OR is used for set elements.

Parameters available

Parameter Description Type Values Required
published Include only published datasets Boolean true/false No
app List of applications datasets should belong to (at least one of them) Text Any text, values separated by commas No
env Include only datasets with at least one of the specified environments Text One or more values from ['production’, 'preproduction’] No
page[size] Maximum number of results returned by the endpoint Number No

Example

Search for datasets with the tag global and water and at least one of the two tags: raster, geospatial. The resulting datasets should also be published and be categorized either as production or preproduction and belong to the application rw. The total number of results returned won’t be limited since a very high number has been provided as limit (999999).

https://api.resourcewatch.org/v1/graph/query/search-datasets?concepts[0][0]=global&concepts[1][0]=water&concepts[2][0]=raster&concepts[2][1]=geospatial&published=true&env=production,preproduction&app=rw&page[size]=999999

{
  "data": [
    "11f43558-d703-4b9d-aff0-f2354a11b359",
    "1b97e47e-ca18-4e50-9aae-a2853acca3f0",
    "20c70a51-4ddf-4f6c-ad2c-1a6729b95fa4",
    "21ac3cd2-9c19-47c7-ad18-4bcad118870f",
    "33bed1fb-9261-41bf-8b50-127a4d0c80c5",
    "3624554e-b240-4edb-9110-1f010642c3f3",
    "36803484-c413-49a9-abe2-2286ee99b624",
    "371e700e-bc9a-4526-af92-335d888de309",
    "60be01b0-99fb-459c-8a08-b934270f8c4b",
    "63a7a997-695d-4629-b6e9-9b169f5c69bf",
    "894f43a8-ce8e-43a5-a4c7-fa80faa43d63",
    "99075509-df36-461e-abb0-659cee555bd0",
    "9e9a5c50-b825-4f12-838f-1650943c2be1",
    "c17fab24-f71a-4c3e-bb87-6b753a944e6b",
    "c9eadefd-4a06-4f3b-a2eb-3e3f45624c24",
    "d7c3d954-ac86-4d1a-bb6a-c8c432a94e26",
    "e63bb157-4b98-4ecb-81d6-c1b15e79895a",
    "e7582657-9c16-4eb1-89e8-0211d94015c6",
    "e94f0e2d-2b5f-41ed-967f-d97e54dd81ea",
    "ede84747-0116-45c2-accb-1dfe141c00ff",
    "f717ac77-6f06-493f-8336-4e660a18f74c",
    "fa6443ff-eb95-4d0f-84d2-f0c91682efdf"
  ]
}

Most liked datasets

This endpoint returns the list of the most liked datasets in descending order.

curl -X GET https://api.resourcewatch.org/v1/graph/query/most-liked-datasets

Example of result

{
    "data": [
        {
            "id": "e2971008-029f-441b-97cd-ee0555728182",
            "count": {
                "low": 2,
                "high": 0
            }
        },
        {
            "id": "f6bb99af-541a-4d41-9e47-cc36cb479d4b",
            "count": {
                "low": 2,
                "high": 0
            }
        },
        {
            "id": "223b936e-06b8-4970-abd9-4f123904d95d",
            "count": {
                "low": 2,
                "high": 0
            }
        },
        {
            "id": "0b9f0100-ce5b-430f-ad8f-3363efa05481",
            "count": {
                "low": 2,
                "high": 0
            }
        },
        {
            "id": "93ee443e-cb39-424a-9aa4-1d16af813418",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "7bcf2f48-8ebd-4900-a485-57a75f9f4e85",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "c18a38cd-94ff-48cd-818f-6ffb05992abb",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "5b5a21ac-0835-43fb-86b9-64b93d472e10",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "fc8cf356-f4be-4635-a896-fb468aaaa832",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "b8307c16-fd77-4e35-9b68-8726a025f401",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "e7c9251c-d39e-4b48-88c5-b2783bb7afdc",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "6e05a9e8-ba07-4e6f-8337-31c5362d07fe",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "3ac5a895-b8ab-4480-b7eb-0fbb452ea76f",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "e2aa09eb-c82e-4977-b614-ef71da5936ce",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "60be01b0-99fb-459c-8a08-b934270f8c4b",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "1ef55baf-bbbe-480d-85e9-7132c742f196",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "3a46f6b4-0eec-49d4-bbfc-e2e8f64e6117",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "d8a45b34-4cc0-42f4-957d-e13b37e9182e",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "80c31f61-6e12-47a0-865d-f33a48bfdebb",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "048b2140-9d4b-433e-a2dd-8d4122eb157b",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "4338471d-881a-475f-8bd9-60c4d48b8e12",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "f84b559f-1eb1-43f2-871f-93fea669bf93",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "9ea634db-53af-445e-a767-60ec9efc321e",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "c02da519-12f3-4c6a-86e7-648afac80b23",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "0a59f415-ee0b-4d19-96f7-c7304c152e1b",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "a07f1bed-ca16-4fbf-b14b-d3a0344cab74",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "f8d3e79c-c3d0-4f9a-9b68-9c5ad1f025e4",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "cefd2836-3cc1-43dc-a9d1-bfecf79a6252",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "63a7a997-695d-4629-b6e9-9b169f5c69bf",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "1b97e47e-ca18-4e50-9aae-a2853acca3f0",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "de452a4c-a55c-464d-9037-8c3e9fe48365",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "c36c3108-2581-4b68-852a-c929fc758001",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "05b7c688-09ba-4f33-90ea-185a1039df43",
            "count": {
                "low": 1,
                "high": 0
            }
        },
        {
            "id": "134caa0a-21f7-451d-a7fe-30db31a424aa",
            "count": {
                "low": 1,
                "high": 0
            }
        }
    ]
}

Areas

The following area endpoints are available

Get user areas

Returns the list of areas created by the user provided

Parameters

Parameter Description Type Values Required
application Application Text Any Text, values separated by commas No
curl -X POST https://api.resourcewatch.org/v1/area?application=<application>
-H "Authorization: Bearer <your-token>"

Example

Areas created by an user for the application RW.

curl -X POST https://api.resourcewatch.org/v1/area?application=rw
-H "Authorization: Bearer <your-token>"
{
  "data": [
    {
      "type": "area",
      "id": "59ca3213d08a7d001054522b",
      "attributes": {
        "name": "Test area France",
        "application": "rw",
        "geostore": "8f77fe62cf15d5098ba0ee11c5126aa6",
        "userId": "58e22f662071c01c02f76a0f",
        "createdAt": "2017-09-26T10:55:15.990Z",
        "image": "",
        "datasets": [

        ],
        "use": {

        },
        "iso": {

        }
      }
    },
    {
      "type": "area",
      "id": "59ca32ea3209db0014e9a7b7",
      "attributes": {
        "name": "Test custom area",
        "application": "rw",
        "geostore": "b12640deba9d3c5012c5359dd5572e2d",
        "userId": "58e22f662071c01c02f76a0f",
        "createdAt": "2017-09-26T10:58:50.226Z",
        "image": "",
        "datasets": [

        ],
        "use": {

        },
        "iso": {

        }
      }
    }
  ]
}

Create area

Creates a new area

Parameters

Parameter Description Type Values Required
application Application Text Any Text, values separated by commas Yes
name Name of the new area Text Any Text Yes
geostore Geostore ID Text Any Text Yes
curl -X POST https://api.resourcewatch.org/v1/area \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": <name>,
   "application": <application>,
   "geostore": <geostore id>
 }'

Example

Create an area with name ‘Portugal area’ and Geostore ID '713899292fc118a915741728ef84a2a7’ for the Resource Watch application

curl -X POST https://api.resourcewatch.org/v1/area?application=rw \
-H "Authorization: Bearer <your-token>" \
-H "Content-Type: application/json"  -d \
 '{
   "name": "Portugal area",
   "application": "rw",
   "geostore": "713899292fc118a915741728ef84a2a7"
 }'
{
  "data": {
    "type": "area",
    "id": "5a0da028e6d876001080c259",
    "attributes": {
      "name": "Portugal area",
      "application": "rw",
      "geostore": "713899292fc118a915741728ef84a2a7",
      "userId": "58e22f662071c01c02f76a0f",
      "createdAt": "2017-11-16T14:26:48.396Z",
      "image": "",
      "datasets": [

      ],
      "use": {

      },
      "iso": {

      }
    }
  }
}

Delete area

Deletes an area

curl -X DELETE https://api.resourcewatch.org/v1/area/<area-id> \
-H "Authorization: Bearer <your-token>" \

Example

curl -X POST https://api.resourcewatch.org/v1/area/59ca3213d08a7d001054522b \
-H "Authorization: Bearer <your-token>" \

Get area

Gets all the information from an area

curl -X GET https://api.resourcewatch.org/v1/area/<area-id> \
-H "Authorization: Bearer <your-token>" \

Example

curl -X GET https://api.resourcewatch.org/v1/area/59ca32ea3209db0014e9a7b7 \
-H "Authorization: Bearer <your-token>" \
{
    "data": {
        "type": "area",
        "id": "59ca32ea3209db0014e9a7b7",
        "attributes": {
            "name": "Test custom area",
            "application": "rw",
            "geostore": "b12640deba9d3c5012c5359dd5572e2d",
            "userId": "58e22f662071c01c02f76a0f",
            "createdAt": "2017-09-26T10:58:50.226Z",
            "image": "",
            "datasets": [],
            "use": {},
            "iso": {}
        }
    }
}

User Management

The following endpoints expose the API’s functionality regarding user management. For more information or implementation details, see the source code.

Login (email + password)

Login endpoints support both HTML and JSON output formats, depending on the Content-type provided in the request. Keep in mind that HTML-based requests will result in redirects - for example, after successfully logging in, you will be taken to /auth/success - while JSON based requests will simply return the matching HTTP code - 200 in case of a successful login.

GET <BASE API URL>/auth/

Convenience URL that redirects to <BASE API URL>/auth/login

GET <BASE API URL>/auth/login

Basic API auth login page. Only supported for HTML requests.

POST <BASE API URL>/auth/login

Endpoint for email + password based login.

For HTML requests, it will redirect to either <BASE API URL>/auth/success or <BASE API URL>/auth/fail depending on whether the login was successful or not. An optional callbackUrl query parameter can be provided, in which case the user will be redirected to that URL in case of login success.

For JSON requests, it will return 200 or 401 HTTP response code depending on whether the login was successful or not. In case of successful logins, the basic user details will be returned as a JSON object.

# Email + password based login - JSON format
curl -X POST http://localhost:9000/auth/login \
-H "Content-Type: application/json"  -d \
 '{
    "email":"your-email@provider.com",
    "password":"potato"
}'
// Response:
{
  "data": {
    "email": "your-email@provider.com",
    "createdAt": "2018-11-15T04:46:35.313Z",
    "role": "USER",
    "extraUserData": {
      "apps": [
        "rw"
      ]
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViZWNmYTJiNjdkYTBkM2VjMDdhMjdmNiIsInJvbGUiOiJVU0VSIiwicHJvdmlkZXIiOiJsb2NhbCIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImV4dHJhVXNlckRhdGEiOnsiYXBwcyI6WyJydyJdfSwiY3JlYXRlZEF0IjoxNTQzMzE1NzMxNzcwLCJpYXQiOjE1NDMzMTU3MzF9.kIdkSOb7mCMOxE2ipqVOBrK7IefAjLDhaPG9DT1qvCw"
  }
}

GET <BASE API URL>/auth/fail

Displays login errors for HTML requests. Not supported on JSON requests.

GET <BASE API URL>/auth/check-logged

Check login status

GET <BASE API URL>/auth/success

Successful login page for HTML requests. Not supported on JSON requests.

GET <BASE API URL>/auth/logout

Login invalidation endpoint

GET <BASE API URL>/auth/generate-token

Generates a JWT token for the current user session.

Login (3rd party oauth)

Registration

Registration endpoints support both HTML and JSON output formats, depending on the Content-type provided in the request.

GET <BASE API URL>/auth/sign-up

Account creation page, for accounts using email + password based login for HTML requests. Not supported on JSON requests.

POST <BASE API URL>/auth/sign-up

Account creation endpoint, for accounts using email + password based login for both HTML and JSON requests.

For HTML requests, it will display a message informing about any validation error, or informing the user in case of success.

For JSON requests, it will return 200 or 422 HTTP response code depending on whether the login was successful or not. In case of successful logins, the basic user details will be returned as a JSON object. In case of failure, an array of errors is returned.

While optional, it’s highly recommended that you specify which apps the user will be granted access to, as most API operation validate the user’s apps match datasets, widgets, etc.

# Account creation using email + password
curl -X POST http://localhost:9000/auth/sign-up \
-H "Content-Type: application/json"  -d \
 '{
    "email":"your-email@provider.com",
    "password":"potato",
    "repeatPassword":"potato"
    "apps" ["rw"]
}'
// Response:
{
  "data": {
    "id": "5bfd237767b3176dd63f2eb7",
    "email": "your-email@provider.com",
    "createdAt": "2018-11-27T10:59:03.531Z",
    "role": "USER",
    "extraUserData": {
      "apps": ["rw"]
    }
  }
}

GET <BASE API URL>/auth/confirm/:token

Endpoint used in the user validation email to confirm the address upon registration.

It accepts an optional callbackUrl query parameter with an URL to which the user will be redirect if the confirmation succeeds.

Should no callbackUrl be provided, the user is redirected to an URL based on the first application associated to their user account - see ct-oauth-plugin configuration for more info.

Should that application have no configured redirect URL, or the user have no configured app, they are redirect to a platform-wide default URL - see ct-oauth-plugin configuration for more info.

Password recovery

Password recovery endpoints support both HTML and JSON output formats, depending on the Content-type provided in the request.

# Password reset
curl -X POST http://localhost:9000/auth/reset-password \
-H "Content-Type: application/json"  -d \
 '{
    "email":"your-email@provider.com"
}'
# New password submission
curl -X POST http://localhost:9000/auth/reset-password/<email token> \
-H "Content-Type: application/json"  -d \
 '{
    "password":"potato",
    "repeatPassword":"potato"
}'

User management

Errors

The Resource Watch API uses the following error codes:

Error Code Meaning
400 Bad Request – Your request is incomplete or contains errors
401 Unauthorized – Your API key is incorrect
403 Forbidden – The kitten requested is hidden for administrators only
404 Not Found – The specified kitten could not be found
405 Method Not Allowed – You tried to access a kitten with an invalid method
406 Not Acceptable – You requested a format that is not json
410 Gone – The kitten requested has been removed from our servers
429 Too Many Requests – You’re requesting too many kittens! Slow down!
500 Internal Server Error – We had a problem with our server. Try again later.
503 Service Unavailable – We’re temporarily offline for maintenance. Please try again later.

API attribution requirements

By using the Resource Watch API, you agree to the Resource Watch terms of service and attribution requirements.