Beginners Guide

Introduction

Sentinel Hub is a cloud based service providing easy access to global archives of analysis-ready Earth Observation data from all the major providers. Currently there are 7 APIs included in our services for a variety of functionalities which allow the user to search, process, analyse, visualize and download satellite data, as well as integrate it into their own application. We have prepared elaborate examples for each API in our documentation for users to get started. In addition, a series of webinars giving a thorough step-by-step instructions to use our services is recommended to be followed by all beginners. Make sure to also see some useful links in the last chapter of this guide.

In this tutorial you will learn how to get started with our services, by learning to run a simple API request. You will be using our Processing API to request satellite images, and Catalog API to find the list of the available images corresponding to your settings.

The guide will present 4 different approaches for you to choose from:

  • Requests Builder - Our user interface application for sending API requests - The easiest way to work with Sentinel Hub API
  • Postman - A third-party user interface application for sending API requests
  • Command line CURL - Running requests in your command line interface
  • Python - A popular framework that makes it possible to use various Python libraries for EO analysis

We strongly recommend you to first go through the Request Builder chapter in detail, and then choose which of the other frameworks you're interested in.

In each section, you will be sending requests from documentation, as well as request a Sentinel-2 image of Lighthouse Reef:

example output

To work with Sentinel Hub API, you will need a Sentinel Hub account. Check the pricing page to learn which packages are available. Note that a 30-day free trial, as well as ESA sponsored accounts are available. Register here.

Requests Builder

Requests Builder is a user-friendly graphical interface designed for easy access to satellite imagery without handling commands, scripting language, and OAuth clients. It is a powerful tool for making API requests and the fastest way to get an image from Sentinel Hub. Getting a response takes just a few clicks, as demonstrated in our Processing API Webinar.

Before we begin, open Requests Builder and make sure you are logged into your Sentinel Hub account, by clicking the Login button on the top right.

login

Run the Example Request From Documentation

  1. Copy the Sentinel-2 true color example request in CURL format from our documentation examples.
  2. Paste the CURL requests to the Request Preview window in Requests Builder (you can find the section on bottom right).
  3. Whenever changes are made in the Request Preview window, make sure to click the Parse button to apply the changes. This will update the user interface with the selected parameters.
  4. By clicking the Send Request button next to a login button on top right, the response of your request will pop up in the same window with a preview thumbnail and be ready for you to download.

run docs request

As you will see, the true color example request from documentation is of landscape in western Slovenia.

example result

This way, you can send any processing Sentinel Hub request in CURL format. For more example requests, please visit the examples page under each data collection in our documentation, e.g., Examples for S2L2A.

Build Your Own Custom Request

It is easy to build a custom request with our Requests Builder by selecting parameters in the graphical user interface. Each time you make a change, the API request will update automatically. The general parts of the Request Builder are the following:

  • API: At the moment there are 7 APIs (Processing API, Batch Processing API, Third Party Data Import API, Catalog API, Statistical API, OGC API and Brind Your Own Cog API) available in Requests Builder. Each one has its own parameters. For getting an image from Sentinel Hub, select Processing API (it's preselected).
  • Data Collection: You can request data from up to 11 data collections with Sentinel Hub. The Bring Your Own COG option allows you to request data from your own data collection that you pre-ingested into Sentinel Hub. The last option on the droplist is DATAFUSION, which allows you to request data from multiple data sources. For this example, select Sentinel-2 L2A.
  • Advanced options: The parameters in this window are specific to each collection. They allow you to control maximum cloud coverage, the mosaicking order, the method of interpolation and more. Additional information can be found in our documentation, under e.g., Sentinel-2 L2A maxCloudCoverage, mosaickingOrder, and processing options.
  • Time Range: Select a specific acquisition date, or a time-range.
  • Area of Interest: Select a desired coordinate reference system from the droplist and draw a polygon or a rectangle over the map to set your area of interest. Alternatively, import a KML/GEOJSON file or paste in the coordinates. Click parse.
  • Output: Specify the output format (TIFF, PNG, JPEG or APP/JSON) and width/height in pixels or x/y resolution in meters.
  • Evalscript: Define the way to process satellite data with Sentinel Hub. Check out the Evalscript (custom script) page for more information.
  • Request Preview: The Request Preview window allows you to directly edit the request body/payload or convert your request between CURL and Python script. The complete parameters of the request body are listed in our API reference.

In the image below, check which options were selected in the Requests Builder to return an image of the easternmost part of the Belize Barrier Reef in the Caribbean Sea. The image is mosaicked with tiles from Sentinel-2 L2A within a time period between 1st of June 2020 and 31st of August 2020.

request lighthouse

The following CURL request is the result of the user interface changes above - it's what you can read from the Request Preview window.

curl -X POST https://services.sentinel-hub.com/api/v1/process \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <your access token>' \
-d '{
"input": {
"bounds": {
"bbox": [
-87.72171,
17.11848,
-87.342682,
17.481674
],
"properties": {
"crs": "http://www.opengis.net/def/crs/EPSG/0/4326"
}
},
"data": [
{
"type": "S2L2A",
"dataFilter": {
"timeRange": {
"from": "2020-06-01T00:00:00Z",
"to": "2020-08-31T23:59:59Z"
},
"maxCloudCoverage": "1"
}
}
]
},
"output": {
"width": 512,
"height": 343.697,
"responses": [
{
"identifier": "default",
"format": {
"type": "image/jpeg"
}
}
]
},
"evalscript": "//VERSION=3\n\nfunction setup() {\n return {\n input: [\"B02\", \"B03\", \"B04\"],\n output: { bands: 3 }\n };\n}\n\nfunction evaluatePixel(sample) {\n return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];\n}"
}'

For a detailed tutorial, please refer to our webinar on Processing API which clearly and comprehensively explains our Processing API service.

Search For Data With Catalog API

To find out which data is available for a given collection, Catalog API can be used. A common use-case is getting a list of acquisition dates in a given time-range, but Catalog can be used for more complex queries as well. The result of a search request with Catalog API is the metadata of all imagery in the library that match the search query in a JSON format. By searching the data availability before requesting the data, users can avoid having empty data reponses and make sure an empty data response is coming from other settings in the request. In this example, we will simply focus on getting a list of acquisitions for Sentinel-2 L1C in a time-range between June 1 and August 31, 2020.

  1. Select API: select CATALOG API.
  2. In the Collections pannel, select a deployment under the Deployment dropdown menu. Different data collections are hosted on different deployments. By selecting a deployment, Requests Builder will automatically fetch the collections for you. To see the full list of available deployments and collections, please refer to the documentation. Next, select your preffered data collection (e.g. Sentinel-2 L1C, Sentinel-1 GRD) from the Data Collection dropdown menu.
  3. Time Range: set your preffered time-range.
  4. Area of Interest: set your area of interest. Requests Builder allows you to insert a bounding box, upload KML/GeoJSON, or directly draw on the map to set the area of interest.
  5. Request Options -> Limit: Limit is used to specify the number of results shown in one page. The default value is 10. After all the settings are set, click the Send Request button to search for data and see the result in the Catalog Results window.
  6. In the Catalog Results window, search results will appear. By expanding one of them, we can inspect additional information about the acquisition.

catalog

In the Request Preview window, you can see how the Catalog request is constructed based on your chosen parameters. As before, you can copy the request into the window and click parse.

curl -X POST https://services.sentinel-hub.com/api/v1/catalog/1.0.0/search \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <your access token>' \
-d '{
"collections": ["sentinel-2-l1c"],
"datetime": "2020-06-01T00:00:00Z/2020-08-31T23:59:59Z",
"bbox": [-87.72171,17.11848,-87.342682,17.481674],
"limit": 10
}'

Postman, CURL CLI and Python

Get Your Client ID and Client Secret

When making Sentinel Hub requests in Postman, CMD CURL or Python, you will need to authenticate so the system can recognize you. The reason this wasn't needed for Requests Builder is because the credentials were read from the user being logged into Sentinel Hub account directly.

Requests are authenticated using an access token, generated from an OAuth client. To get an access token, your Sentinel Hub Client ID and Client Secret (strings of randomly generated characters) need to be specified.

Before we start, Sign in to your Sentinel Hub account. You can always access the Sign In button from the top right of the Sentinel Hub website as well.

To get your Client Secret and Client ID, follow the steps in the Registering OAuth client guide.

You will use the Client ID and Client secret to access the Sentinel Hub APIs later.

Note: Access tokens expire after an hour. To fix this, just request a new access token.

Postman

Postman is a third-party application for sending API requests. In this section, you will learn how to import any request, including our request collections, authenticate and run the requests. See also the Processing API Webinar, where you can see the steps below in a video.

This chapter covers two options: how to work with any single CURL request in Postman, and how to work with request collections from our documentation. The three subchapters - Import Requests to Postman, Authorization in Postman and Send the Request - cover the two options separately.

Import Requests to Postman

Import a Single CURL Request to Postman

  1. Click "Import" on the top left.
  2. Select the "Raw Text" tab.
  3. Copy any CURL request from our documentation (for example this one into the "Raw text" window.
  4. To confirm, scroll down to find the orange Continue button.

request import

To authorize a single request, jump to the chapter Authorize a Single Request.

Import Example Collection to Postman

For each data collection, we have prepared a Postman collection with example requests on our documentation page, e.g., Examples for S2L2A. Clicking on downloaded here will open the collection in a new browser tab. Right click and select save-as, to save the JSON file to your computer. Follow the steps below to import it and get the first example image.

postman download

To import an example collection to Postman, follow the steps below:

  1. Click "Import" on the top left.
  2. Select the "File" tab.
  3. Click "Upload files" and select the downloaded JSON file on your computer.
  4. Click the orange "Import" button to confirm.

import collection

To authorize a collection, jump to the chapter Authorize the Collection.

Authorization in Postman

Authorize a Single Request

  • Click the request you want to authorize from the menu on the left.
  • In the request tabs, select the Authorization tab.
  • Set the authorization parameters as follows (leave all not mentioned fields as they are):
    • Type: OAuth 2.0
    • Add auth data to: Request Headers
    • Header Prefix: Bearer
    • Token Name: <your_token_name>
    • Grant Type: Client Credentials
    • Access Token URL: OAuth2 Endpoints
    • Client ID: <your_OAuth_client_id>
    • Client Secret: <your_OAuth_client_secret>
    • Client Authentication: Send as Basic Auth header
  • Click Get New Access Token button to generate the token.
  • In the Authentication complete dialog box, click Proceed.
  • In the Manage access tokens dialog box, click Use Token to use the generated token.

request auth

To send the request, see the chapter Send the request.

Authorize the Collection

It's recommended to organize your requests by collections, and then authenticate the whole collections with the requests inheriting the access token from it. This way, you only need to get an access token once every hour. To authorize a collection, follow the steps below:

  • Click the imported collection in the sidebar on the left
  • Click the three dots next to the collection name (1), and click Edit (2).
  • In the Edit dialog box, select the Authorization tab (3).
  • Set the authorization parameters as follows (leave all not mentioned fields as they are) (4):
    • Type: OAuth 2.0
    • Add auth data to: Request Headers
    • Header Prefix: Bearer
    • Token Name: <your_token_name>
    • Grant Type: Client Credentials
    • Access Token URL: OAuth2 Endpoints
    • Client ID: <your_OAuth_client_id>
    • Client Secret: <your_OAuth_client_secret>
    • Client Authentication: Send as Basic Auth header
  • Click Get New Access Token button (5) to generate the token.
  • In the Authentication complete dialog box, click Proceed (6).
  • In the Manage access tokens dialog box, click Use Token (7) to use the generated token.
  • Click Update to update the collection settings (8).

authenticate collection

For this to work, each request in the collection has to have the authentication type set to "Inherit auth from parent". To check this, click on each request in your collection and open the Authorization tab. Make sure that Type is set to "Inherit auth from parent". In our example collections from documentation, this should already be set.

inherit

Send the Request

Once the authentication process is done, click on any example request in the sidebar on the left. To inspect the request body and evalscript, click on the body tab in the request. Clicking the blue Send button will send the request, and you will see an image displayed in the Body window below. To download it, expand the arrow next to the Send button and click Send and Download.

request

To make a Catalog request in Postman, simply import a request or a whole example collection from Catalog Examples, as shown above. Below, a simple POST search request was imported and authorized, searching for 5 available results of Sentinel-1 GRD data in a given time-range. In this case, the result after sending the request will be a JSON file, and not an image.

catalog result

CURL

CURL is a tool which sends requests through the command line interface (CLI). If you are using Windows 10, macOS, or Linux you probably already have it pre-installed. Otherwise you can install it here.

Open Your CLI

The command line interface, also called a CLI, is a program which makes it possible to send instructions to your computer via text commands. Which command line interface you will be using for this tutorial depends on your operating system:

  • Windows: Git Bash
  • Mac: Terminal, comes pre-installed
  • Linux: Bash, comes pre-installed

Authorization With Access Token

You can now get started with running CURL requests through your command line interface. The first thing you will do is use your Client ID and Client Secret to get an access token. The access token will be the way you identify yourself when making requests.

  1. Copy the CURL command below to a text editor:
curl -X POST --url https://services.sentinel-hub.com/auth/realms/main/protocol/openid-connect/token --header "content-type: application/x-www-form-urlencoded" --data "grant_type=client_credentials&client_id=<your client id>" --data-urlencode "client_secret=<your client secret>"
  1. Replace <your client id> and <your client secret> with your own Client ID and Client Secret generated from the Sentinel Hub Dashboard.
  2. Paste the entire command set with your own client id and client secret to your command line interface and press enter. The response you get is the access_token which is a long string containing letters, numbers, and special characters as shown below. Make sure to save the access_token to a text editor for later.

cmd

To make the above more clear, Client Secret and Client ID in the example above were }m%>Zt/9E5+EPsT_zY-y^2(vi-,c*G>L-)p)dj75 and ed05a0e6-9aec-4d5a-aaf8-af07333760b8, respectively. The access token is the long string between the two " signs. The resulting access token from the request above is:

eyJraWQiOiJzaCIsImFsZyI6IlJTMjU2In0. eyJzdWIiOiJiNGNjMTEyOC1lZWUzLTQ0OGMtOWViZC1jNWE2NmRkY2UwMjgiLCJhdWQiOiJlZDA1YTBlNi05YWVjLTRkNWEtYWFmOC1hZjA3MzMzNzYwYjgiLCJqdGkiOiIwNzFhMDEwZC04ZDk4LTRkNzItYWQ3My1jNzZlMWExZTk0NjIiLCJleHAiOjE2MzI3ODA2NTEsIm5hbWUiOiJNb25qYSDFoGViZWxhIiwiZW1haWwiOiJtb25qYS5zZWJlbGErdGVtcG9yYXJ5QHNpbmVyZ2lzZS5jb20iLCJnaXZlbl9uYW1lIjoiTW9uamEiLCJmYW1pbHlfbmFtZSI6IsWgZWJlbGEiLCJzaWQiOiI0OTJmNzRlMC0zM2ZhLTRmZDEtYTJmNi0wNmU4ZjUwMzNhYzUiLCJkaWQiOjEsImFpZCI6ImY3M2ZjZGJhLWIzYjItNDA3Mi1iYzE2LTQ3ZWU4YTk5OTEyOSIsImQiOnsiMSI6eyJyYSI6eyJyYWciOjF9LCJ0IjoxMTAwMH19fQ. hA2oDRQaNz-1Tqf09U4K06g7K5ppL17UQHE7TIKrq2hTsCHFU-iDGMsHCWTLsrT_HBIJ6KGwMo6qXpGIPgN6d146BgdEXlbYCNKa4jxtGf0vzRfdJN9-5n-lkOyvVXzIv6Ont09Sfgvx0dOf0YvpaR1vNvNVGfjV2y-v18MwsstkKFSiDId9nLHxblhKVMNgBnVtmGfcCG4Rn7m4xWfAh5Gmg3_PLCJgDbYeBMMLqURooBmlwCj25497OZPWDQPwabW-QU4U4YdB7ynT6UL0X8Kp9yua9MqSmJin8n02jflI9FlfHKxfq4vmvqOiUN37ITgX2OMLYt4ELJGFTAAylA`

Note: Access tokens expire after an hour. To fix this, just request a new access token and replace it in your requests.

Request an Image

  1. Copy any CURL request (for example the S2L2A true color image request example to a text editor.
  2. Replace <your access token> on top with access_token you got from the previous request. When doing so, be careful not to add or delete any " and ' signs.
  3. Add the > satellite-image.jpg code at the end of the request from documentation. This will make sure the image is saved to your computer.

The below CURL example is of Lighthouse Reef, with a code for image download added, but without the inserted access token.

curl -X POST \
https://services.sentinel-hub.com/api/v1/process \
-H 'Authorization: Bearer <your access token>' \
-F 'request={
"input": {
"bounds": {
"properties": {
"crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84"
},
"bbox": [
-87.72171,
17.11848,
-87.342682,
17.481674
]
},
"data": [
{
"type": "S2L2A",
"dataFilter": {
"timeRange": {
"from": "2020-06-01T00:00:00Z",
"to": "2020-08-31T23:59:59Z"
},
"maxCloudCoverage": "1"
}
}
]
},
"output": {
"width": 1024,
"height": 1024
}
}' \
-F 'evalscript=//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: {
bands: 3,
sampleType: "AUTO"
}
}
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02]
}'

After adding the access token, the request looks like this (do replace the access token with your own):

curl -X POST https://services.sentinel-hub.com/api/v1/process \
-H 'Authorization: Bearer <your access token>' \
-F 'request={
"input": {
"bounds": {
"properties": {
"crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84"
},
"bbox": [
-87.72171,
17.11848,
-87.342682,
17.481674
]
},
"data": [
{
"type": "S2L2A",
"dataFilter": {
"timeRange": {
"from": "2020-06-01T00:00:00Z",
"to": "2020-08-31T23:59:59Z"
},
"maxCloudCoverage": "1"
}
}
]
},
"output": {
"width": 1024,
"height": 1024
}
}' \
-F 'evalscript=//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: {
bands: 3,
sampleType: "AUTO"
}
}
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02]
}'
  1. After your access token is added to the request, paste the entire request to your command line interface and press enter.

The response will look similar to the one shown below, and your actual satellite image will be saved in the current working directory, where your command line interface is open. If you are not sure which directory that is, you can type pwd into your command line interface and it will show you the output folder.

cli request response

Search For Data With Catalog API

The following request will return 1 search result for Sentinel-2 L2A in a given AOI, within the time period 1.6.2020 - 31.8.2020.

  1. Copy the request example below and make sure to replace <your access token> with access_token you got from the authentication request. Instead of the following request, you can use any request from our Catalog examples.
curl -X POST https://services.sentinel-hub.com/api/v1/catalog/1.0.0/search \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <your access token>' \
-d '{
"collections": ["sentinel-2-l2a"],
"datetime": "2020-06-01T00:00:00Z/2020-08-31T23:59:59Z",
"bbox": [-87.72171,17.11848,-87.342682,17.481674],
"limit": 1
}'
  1. Paste the request with inserted access token to your CLI and press enter.

The result of the request should look something like this:

cli catalog response

Adding > catalog-request.json at the end of the code above will download the response into a JSON file. To make it more readable, you might want to copy the response into an online JSON formatter.

Python

Follow the steps below to see how to set up Python and run Sentinel Hub requests in it. To learn more, find additional information on this website for useful links on Sentinel Hub Python package and our eo-learn blog posts. You can also find several Python example notebooks for our various APIs on our GitHub page, and several use case notebooks on our education page.

Note that Python 3.6 or newer is required to run the examples from documentation. Follow the instructions below to set it all up.

Set Up a Virtual Environment

Since there are several modules/packages that need to be installed to run Sentinel Hub services, you might want to set up an environment specific for it to avoid compatibility issues. This would also be helpful to prevent you from messing up your system. If you accidentally do something wrong in the environment, you can always remove it and create a new one without any effect to your root system. Follow the steps below to set up a Conda environment and run Sentinel Hub services within it.

1. Install Anaconda

Please refer to Anaconda documentation for the instruction of installing Anaconda on Windows/macOS/Linux.

2. Create a virtual environment

  • Launch the Anaconda navigator.
  • Click Environments (1) and then Create (2).
  • Name your environment (3) and select the latest version of Python (4). Note that Python 3.6 or newer is required to run the examples from documentation.
  • Click Create (5).

anaconda make new

3. Install requisite Python packages

  1. In the environments tab, search for your newly created environment by name.
  2. Select Not installed from the drop-down list.
  3. Search for oauthlib, requests-oauthlib, matplotlib and notebook in the search box on the top right. (See the Alternative approach below if you can't see the packages listed)
  4. Tick the box on the left of each of the 4 packages to select it.
  5. When all 4 packages are selected, click Apply.
  6. Click Apply again in the pop-out window to install the selected packages.

anaconda install

Note: It is recommneded to install all the packages at once, so Anaconda can handle the compatibility for you.

Alternative approach

If package installation using Anaconda user interface doesn't work for you, you can install the packages using the command line interface instead.

  1. Click the play button next to your environment and select Open Terminal.

anaconda open terminal

  1. Paste in the conda install -c conda-forge oauthlib requests-oauthlib matplotlib notebook command and press enter.

anaconda activate env

  1. When asked if you wish to proceed, type y and press enter confirm.

anaconda install packages terminal

4. Launch a Jupyter Notebook

  1. Click Home.
  2. Select the environment you created from the drop-down list.
  3. Find Jupyter Notebook and click Launch to open the jupyter notebook in your default browser.

notebook launch

Note: When launching the Jupyter Notebook, make sure you are in the environment with all the required packages installed. This is important after shutting down the computer, as the environment will automatically move to root and you will have to activate it again (to activate an environment, just select it in Anaconda Navigator).

Alternative Approach

If you can't open a Jupyter Notebook using Anaconda user interface, you can run it directly in command line interface instead.

  1. Make sure the terminal is open from your virtual environment, where you installed the requisite packages (see the previous chapter).
  2. To do so, write jupyter notebook and press enter.

5. Open a new notebook

Click New and select Python 3 to open a new notebook.

open python

If you're not familiar with Jupyter Notebook, see this beginner tutorial to learn how to use it. Most importantly: the cells are run with CTRL+Enter. Note that you need to run each cell separately in top to bottom order.

Make a Request

The steps below were collected in a Jupyter Notebook, that you can import into your Jupyter Notebook by clicking Upload. Each step, as well as how to construct Python body request, is explained below.

1. Import requisite packages

Copy these imports to your Jupyter Notebook to import all the needed libraries.

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
from PIL import Image
import io
import numpy as np
import matplotlib.pyplot as plt

2. Authentication

Add this code to your notebook next, and replace <your client id> and <your client secret> inside the quotation marks with your client id and client secret:

CLIENT_ID = "<your client id>"
CLIENT_SECRET = "<your client secret>"

For example:

CLIENT_ID = "ed05a0e6-9aec-4d5a-aaf8-af07333760b8"
CLIENT_SECRET = "}m%>Zt/9E5+EPsT_zY-y^2(vi-,c*G>L-)p)dj75"

The following code will set up credentials for use with our APIs and get an authentication token (no need to change anything here, just copy this code to your Notebook next).

# set up credentials
client = BackendApplicationClient(client_id=CLIENT_ID)
oauth = OAuth2Session(client=client)
# get an authentication token
token = oauth.fetch_token(token_url='https://services.sentinel-hub.com/auth/realms/main/protocol/openid-connect/token',
client_secret=CLIENT_SECRET, include_client_id=True)

3. Set the parameters for the image request

The variable parameters are set here and referenced in the request below. This way, it's easy for you to edit the BBOX, time-range or collection type.

  • bbox: Find the bounding box of your AOI via our Requests Builder
  • start_date and end_date: these are your time interval start and end dates. Fill them in using this format: 'YYYY-MM-DD'
  • collection_id: Choose a data collection and look up its collection identifier at the bottom of the page; for example, for Sentinel-2 L2A, the identifier is sentinel-2-l2a.
bbox = [-87.72171, 17.11848, -87.342682, 17.481674]
start_date = "2020-06-01"
end_date = "2020-08-31"
collection_id = "sentinel-2-l2a"

4. Create an evalscript and request body/payload

It's easy to get an evalscript and request body payload for Python from any CURL request. The best way to do it is to parse the request in Requests Builder, then grab the relevant parts and copy them into Python code.

  • First, check the chapter of Requests builder called Run the example request from documentation to see how to grab any example from our documentation and parse it.
  • When the request is parsed, copy the evalscript from Requests Builder (Image below - 1) and paste it into the following code, replacing the <copied evalscript> part. Note that the evalscript goes between two tripple quotes """, which signify a multiline comment in Python.
evalscript = """
<copied evalscript>
"""

Let's use a simple true color composite visualization from this example. After adding it, the Python code should look like this:

evalscript = """
//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: {
bands: 3,
sampleType: "AUTO" // default value - scales the output values from [0,1] to [0,255].
}
}
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02]
}
"""
  • In Requests Builder Request Preview, select body from the dropdown menu (2).
  • Copy the code from Request Preview, but only up to a comma before evalscript, so the "evalscript" is excluded, and a comma included, as demonstrated in orange on the image below (3).

copy body

  • Use the copied request to replace the <copied payload> in the following Python code:
json_request = <copied payload>
"evalscript": evalscript
}

Using the CURL request body for Lighthouse Reef, the result would look like this:

json_request = {
"input": {
"bounds": {
"bbox": [
-87.72171,
17.11848,
-87.342682,
17.481674
]
},
"data": [
{
"dataFilter": {
"timeRange": {
"from": "2020-06-01T00:00:00Z",
"to": "2020-08-31T23:59:59Z"
},
"maxCloudCoverage": "1"
},
"type": "sentinel-2-l2a"
}
]
},
"output": {
"width": 1024,
"height": 1026.707,
"responses": [
{
"identifier": "default",
"format": {
"type": "image/jpeg"
}
}
]
},
"evalscript": evalscript
}

Putting both, evalscript and request body together, the final Python request would look like this:

# evalscript
evalscript = """
//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: { id: 'default',
bands: 3 }
};
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
}
"""
# request body/payload
json_request = {
'input': {
'bounds': {
'bbox': bbox,
'properties': {
'crs': 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'
}
},
'data': [
{
'type': 'S2L2A',
'dataFilter': {
'timeRange': {
'from': f'{start_date}T00:00:00Z',
'to': f'{end_date}T23:59:59Z'
},
'mosaickingOrder': 'leastCC',
},
}
]
},
'output': {
'width': 1024,
'height': 1024,
'responses': [
{
'identifier': 'default',
'format': {
'type': 'image/jpeg',
}
}
]
},
'evalscript': evalscript
}

6. Set the request url and headers for the Processing API and send the request

The following code will specify the Processing API endpoint, set up headers and send the request. In this step, the request will be executed, but the results won't yet be displayed. If you are using Processing API, you can leave this part as is, otherwise you will need to edit the endpoint (/api/v1/process in the url_request lets Python know that Sentinel Hub Processing API is being used).

# Set the request url and headers
url_request = 'https://services.sentinel-hub.com/api/v1/process'
headers_request = {
"Authorization" : "Bearer %s" %token['access_token']
}
#Send the request
response = oauth.request(
"POST", url_request, headers=headers_request, json = json_request
)

Display the Requested Image

1. Get the image array and plot the image

When the request above is successful, this piece of code will display a requested image (in this case, the image of Lighthouse Reef). You may paste this code in as is, and you can edit the image size by changing the figsize numbers.

# read the image as numpy array
image_arr = np.array(Image.open(io.BytesIO(response.content)))
# plot the image for visualization
plt.figure(figsize=(16,16))
plt.axis('off')
plt.tight_layout()
plt.imshow(image_arr)

Search for Available Data With Catalog API

1. Import requisite packages, authenticate, and set parameters

Follow the steps 1, 2 and 3 of the Make a request section for Python. If your Notebook already icludes these from requesting an image, there's no need to add them again.

2. Create the request body/payload

The Catalog request below will return all the available acquisitions, that match the specified parameters - time-range, collection, bbox and the number of results. These parameters were already defined above, in Make a Request - point 3, and are being referenced here again. Defining the parameters separately makes it easy to quickly change them (e.g. change the bbox) without the need to edit every request. You could of course specify them again.

json_search = {
'bbox': bbox,
'datetime': f'{start_date}T00:00:00Z/{end_date}T23:59:59Z',
'collections': [collection_id],
'limit': 1
}

Instead of this request, we could easily use any Catalog request from documentation, such as for example this one. As Catalog examples are written in Python, they can be copied in as they are.

3. Set the endpoint and send the request

The following code will specify the endpoint for Catalog API, set up headers and send the request. Note that the endpoints differ for each API - for example, Catalog API has /catalog/search in URL, while Processing API has /process. This is how the system knows which API you are using. In this step, the request will be executed, but the results won't yet be displayed.

# set the url and headers
url_search = 'https://services.sentinel-hub.com/api/v1/catalog/search'
headers_search = {
'Content-Type': 'application/json'
}
# send the request
response_search = oauth.request(
"POST", url_search, headers=headers_search, json = json_search
)

4. Print the search result

The following code will print the result of the Catalog search in JSON format.

response_search.json()

The JSON result will look something like this. As the search was limited to only 1 result, you can see how the Catalog response looks like for a single acquisition.

{'type': 'FeatureCollection',
'features': [{'stac_version': '0.9.0',
'stac_extensions': ['eo', 'projection'],
'id': 'S2B_MSIL2A_20200829T160829_N0214_R140_T16QDD_20200829T202913',
'type': 'Feature',
'geometry': {'type': 'MultiPolygon',
'crs': {'type': 'name',
'properties': {'name': 'urn:ogc:def:crs:OGC::CRS84'}},
'coordinates': [[[[-87.94071585394981, 17.182790096139676],
[-87.93587348395916, 16.19036949655277],
[-86.9086993551878, 16.192409486612753],
[-86.9082268661048, 17.184962449040317],
[-87.94071585394981, 17.182790096139676]]]]},
'bbox': [-87.94071585394981,
16.19036949655277,
-86.9082268661048,
17.184962449040317],
'properties': {'datetime': '2020-08-29T16:28:57Z',
'platform': 'sentinel-2b',
'instruments': ['msi'],
'constellation': 'sentinel-2',
'eo:gsd': 10,
'eo:cloud_cover': 0.0,
'eo:bands': [{'name': 'B01',
'common_name': 'coastal',
'center_wavelength': 0.4427,
'full_width_half_max': 0.021},
{'name': 'B02',
'common_name': 'blue',
'center_wavelength': 0.4924,
'full_width_half_max': 0.066},
{'name': 'B03',
'common_name': 'green',
'center_wavelength': 0.5598,
'full_width_half_max': 0.036},
{'name': 'B04',
'common_name': 'red',
'center_wavelength': 0.6646,
'full_width_half_max': 0.031},
{'name': 'B05',
'center_wavelength': 0.7041,
'full_width_half_max': 0.015},
{'name': 'B06',
'center_wavelength': 0.7405,
'full_width_half_max': 0.015},
{'name': 'B07', 'center_wavelength': 0.7828, 'full_width_half_max': 0.02},
{'name': 'B08',
'common_name': 'nir',
'center_wavelength': 0.8328,
'full_width_half_max': 0.106},
{'name': 'B8A',
'common_name': 'nir08',
'center_wavelength': 0.8647,
'full_width_half_max': 0.021},
{'name': 'B09',
'common_name': 'nir09',
'center_wavelength': 0.9451,
'full_width_half_max': 0.02},
{'name': 'B11',
'common_name': 'swir16',
'center_wavelength': 1.6137,
'full_width_half_max': 0.091},
{'name': 'B12',
'common_name': 'swir22',
'center_wavelength': 2.2024,
'full_width_half_max': 0.175}],
'proj:epsg': 32616,
'proj:bbox': [399443.3416020406,
1789993.1753013658,
509809.6045306196,
1900259.347750869],
'proj:geometry': {'crs': {'type': 'name',
'properties': {'name': 'urn:ogc:def:crs:EPSG::32616'}},
'coordinates': [[[[399960.99999997736, 1900018.9999599545],
[399960.99999998347, 1790220.9999620381],
[509758.9999999999, 1790220.9999620395],
[509758.9999999999, 1900018.9999599562],
[399960.99999997736, 1900018.9999599545]]]]}},
'links': [{'href': 'https://services.sentinel-hub.com/api/v1/catalog/collections/sentinel-2-l2a/items/S2B_MSIL2A_20200829T160829_N0214_R140_T16QDD_20200829T202913',
'rel': 'self',
'type': 'application/json'},
{'href': 'https://services.sentinel-hub.com/api/v1/catalog/collections/sentinel-2-l2a',
'rel': 'parent'},
{'href': "https://scihub.copernicus.eu/dhus/odata/v1/Products('783cd11b-8a97-4696-815f-b2d935c7858a')/$value",
'rel': 'derived_from',
'title': 'scihub download'}],
'assets': {'data': {'href': 's3://sentinel-s2-l2a/tiles/16/Q/DD/2020/8/29/0/',
'title': 's3',
'type': 'inode/directory'}}}],
'links': [{'href': 'https://services.sentinel-hub.com/api/v1/catalog/search',
'rel': 'self',
'type': 'application/json'},
{'href': 'https://services.sentinel-hub.com/api/v1/catalog/search',
'rel': 'next',
'type': 'application/json',
'title': 'Next set of results',
'method': 'POST',
'body': {'next': 1},
'merge': True}],
'context': {'next': 1, 'limit': 1, 'returned': 1}}

Some useful links:

  • Sentinel Hub Home Page - Sentinel Hub website with EO Browser documentation, education resources, industry examples, instructions on data integration, community contributions, FAQ and more.
  • Sentinel Hub Documentation - Technical API documentation (= this website).
  • Available Data Collections - List of all API supported data collections, deployments, request examples and available parameters.
  • Sentinel Hub Webinars - A list of tutorial webinars for beginners.
  • Custom scripts - How to control satellite visualization and values (including data fusion and multi-temporal scripting).
  • Custom Script Repository - A public repository of satellite visualizations
  • EO Browser - our free web application that showcases the functionalities of Sentinel Hub. Search, view, analyze and download EO data on the fly.
  • Pricing - See the available Sentinel Hub packages.
  • ESA sponsored accounts - Get a Sentinel Hub account sponsored by ESA for research or precommercial exploitation purposes.
  • Requests Builder - A web application with intuitive user interface for easy API request sending and construction.
  • Sentinel Hub API Overview - Information on API authentication, rate limiting, processing units and error handling.
  • API Reference - Detailed overview of the available parameters and their structure for each API.
  • Sentinel Hub GitHub - Public GitHub repositories with sh.js, sh.py, application code and more.
  • Integration of Sentinel Hub with GIS applications - Integrate satellite imagery into ArcGIS, QGIS, with Python and more.

Sentinel Hub offers the following APIs, all accessible on this website:

Note that each of the API's and data collections has a list of most commonly used request examples available.