Integrate SpaceSense API
Description
This section will show you how to use the API in a simple way using a practical example by creating a proof a concept project covering all major axes of SpaceSense API along
with the integration of the result on a world map using either Google map js, leafletjs or Mapbox.
The tutorial will follow the clasic integration process in the following order :
- Login
- Register Fields
- Get Satelite Insight
- Integrate in your system
This Tutorial covers the basics of everything, if you are looking for something more specific we suggest you a couple of pages you might be intrusted in
Login
To access the API and start writing and reading data you need to login.
You recieved your credentials in your first Email in the form of:
Username: custom-username
Password: secure-password
This tutorial doesn't cover your favorite language let us know: support@spacesense.ai
#import requests
import requests
# Creating the load for the request.
# replace custom-username and secure-password by your SpaceSense username and password
pload = {'username':'custom-username','password':'secure-password'}
# send the request a a post to the API adress and adds the load to the request
r = requests.post('https://spacesense-api.ew.r.appspot.com/login', data = pload)
# get the response Json in a dictionary.
r_dictionary = r.json()
# this is your API token for this session. you need to store and it and keep it.
token = r_dictionary['token']
// Creates an instance of HttpClients
HttpClient client = HttpClient.newHttpClient();
// Create a new Post on the API for the Login endpoint
HttpRequest request = HttpRequest.newBuilder(URI.create("https://spacesense-api.ew.r.appspot.com/login"))
.build();
// Creates a List to add parameters to the post request
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
// Change custom-username to your SpaceSense API username
params.add(new BasicNameValuePair("username", "custom-username"));
// Change secure-password to your SpaceSense API password
params.add(new BasicNameValuePair("password", "secure-password"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Create the Token variable
String token;
if (entity != null) {
try (InputStream instream = entity.getContent()) {
BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
// this is your API token for this session. you need to store and it and keep it.
token = myResponse['token']
}
curl -d 'username=custom-username&password=secure-password' https://spacesense-api.ew.r.appspot.com/login
Upon successful login you will recieve a token from the API now stored in the token
variable.
This token is required to talk to the API.
For every request you'll send to the API (except Login) you will add your token like a GET
request parameter.
Example : https://api-address/endpoint?token=__myToken__
in this example the token is __myToken__
Registering new fields
The SpaceSense API let you register new fields using a specific json format called GeoJson
This section covers how to send a geojson to the API in order to register new fields.
Geojson
Geojson is an open standard format designed for representing simple geographical features using GPS coordinates.
GeoJson let you draw all different kinds of shapes or landmarks.
For the sake of this API's use you will only use GeoJson Polygon feature to register new fields.
Need more informations about GeoJson ? checkout those websites :
Create a Json body for the request
To register a new field you will need a GeoJson representing a polygon you can use Geojson.io to generate new Geojson.
Like this :
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[3.431151509284973, 45.583409896815034],
[3.4310495853424072, 45.58235490155467],
[3.432530164718628, 45.58246002652684],
[3.432524800300598, 45.58345870394514],
[3.431151509284973, 45.583409896815034]
]
]
}
}
]
}
NOTE : The first part (type, features, properties, etc . . .) is part of the GeoJson format. Remove it and your field won't get processed.
Now that you know what a GeoJson looks like, let's register a new Field.
Register new fields
The Polygon is not the only information we need to give the API, you need to build a complete Json body for the request.
Create a json and add a Field name as a string, an array of labels you want for this field, a geojson.
let's start with NDVI and a custom label (Farmer-34) to show how you can organize your fields.
Checkout the API documentation for this endpoint for more informations
The final Json will look something like that :
{
"field_name": "farm_9",
"label": ["NDVI", "Farmer-34"],
"geojson": {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-4.391269683837891, 39.71808094723828],
[-4.388244152069092, 39.71149505915214],
[-4.3865275382995605, 39.7120727937937],
[-4.387707710266113, 39.717800358315465],
[-4.391269683837891, 39.71808094723828]
]
]
}
}
]
}
}
This json will be referenced as __myJsonBody__
in the rest of this tutorial
To register a new Field you will need __myJsonBody__
and your Identification token referred to as __myToken__
in those examples.
curl -h "Content-Type: application/json" -d __myJsonBody__ https://spacesense-api.ew.r.appspot.com/fields/register?token=__myToken__
#import requests & json libraries
import requests
import json
# Sends a post request using your identification Token and the Json previously built
r = requests.post('https://spacesense-api.ew.r.appspot.com/fields/register?token=' + __myToken__, json = json.loads(__myJsonBody__))
After registering a field
Display the results on a map
In this section you will see how you can display the processed data using this API and an interactive map
This tutorial won't go over everything you need to know to use the map providers in detail. here are a couple of links to the dedicated documentations.
// Create a ground overlay variable so you can update the overlay.
let groundOverlay;
// Initiating google map visualisation
// ref: https://developers.google.com/maps/documentation/javascript/overview
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 40.74, lng: -74.18},
});
// change the bounds with the new bounds from the json file
// look at download with extention in in SpaceSense doc
// ref : https://spacesense.gitlab.io/product_support/developer_site/docs/API/download_file/#response-details--json
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(jsonData.bounds[0][0], jsonData.bounds[0][1]),
new google.maps.LatLng(jsonData.bounds[1][0], jsonData.bounds[1][1])
);
// path to png image (can be a link to the api or a local file).
// ref: https://spacesense.gitlab.io/product_support/developer_site/docs/API/download_file/#image
var srcImage = 'image_path.png';
// create the ground overlay
// ref : https://developers.google.com/maps/documentation/javascript/examples/groundoverlay-simple
groundOverlay = new google.maps.GroundOverlay(srcImage, imageBounds);
// assign the ground overlay to your map
groundOverlay.setMap(map);
// Create the overlay variable so you can update in instead of creating a new one.
let imageOverlay;
// Initiating leaflet map visualisation
// ref : https://leafletjs.com/reference-1.7.1.html#map-example
var map = L.map('map', {
center: [51.505, -0.09],
zoom: 13,
});
// add bounds from the json file
// look at download with extention in SpaceSense doc
// ref : https://spacesense.gitlab.io/product_support/developer_site/docs/API/download_file/#response-details--json
// ref : https://leafletjs.com/reference-1.7.1.html#latlngbounds
var imageBounds = [
[40.712216, -74.22655],
[40.773941, -74.12544],
];
// path to png image (can be a link to the api or a local file).
// ref: https://spacesense.gitlab.io/product_support/developer_site/docs/API/download_file/#image
var imageUrl = 'image_path.png';
// create the image overlay
// ref : https://leafletjs.com/reference-1.7.1.html#imageoverlay
imageOverlay = L.imageOverlay(imageUrl, imageBounds);
// assign the overlay to your map
// ref : https://leafletjs.com/reference-1.7.1.html#imageoverlay-addto
imageOverlay.addTo(map);
// Create the overlay variable so you can update in instead of creating a new one.
let imageOverlay;
// Initiating mapbox map visualisation
// ref : https://docs.mapbox.com/mapbox.js/api/v3.3.1/l-mapbox-map/
var map = L.mapbox.map('map', 'mapbox.satellite').setView([40, -74.5], 9);
// add bounds from the json file
// look at download with extention in SpaceSense doc
// ref : https://spacesense.gitlab.io/product_support/developer_site/docs/API/download_file/#response-details--json
// ref : https://docs.mapbox.com/mapbox.js/api/v3.3.1/l-latlngbounds/
var imageBounds = [
[40.712216, -74.22655],
[40.773941, -74.12544],
];
// path to png image (can be a link to the api or a local file).
// ref: https://spacesense.gitlab.io/product_support/developer_site/docs/API/download_file/#image
var imageUrl = 'image_path.png';
// create the image overlay and assign it to your map
// ref : https://docs.mapbox.com/mapbox.js/api/v3.3.1/l-imageoverlay/
imageOverlay = L.imageOverlay(imageUrl, imageBounds).addTo(map);
Recap
We just learned how to login, add fields to your spacesense account, get data from processed fields and finaly display that data.
You should now checkout some more API features in the Documentation
here are a few usefull links :