Skip to content

Get data from a REST API

There is a plug-and-play connector for REST API in Serenytics. But in many cases, the API has a custom format and needs a few lines of Python to be used. Here is a small example to show you how easy it is to write a script that connects to a REST API, grabs some data and loads it within a Serenytics storage.

import serenytics
import requests

# create the serenytics client
client = serenytics.Client()

# -- get the data
url = 'my_url'
headers = {
    'content-type': 'application/json',
    'X-API-Key': 'my api key for the API'
}
payload = {
  'param1': 'today',
  'param2': 'this is a test'
}

response = requests.post(url, headers=headers, json=payload)
print(response.status_code)

if r.status_code==200:
    print(response.json())

    # -- load it into a Serenytics storage
    source = client.get_or_create_storage_data_source_by_name(name='my storage')

    # in this example, I pass response.json() straight to source.reload_data().
    # In a real example, you'll certainely need to reformat the data before
    # sending it to Serenytics.
    source.reload_data(new_data=response.json())

This script is very self-explicit. If you want to go further, read the python documentation for the excellent Python package Requests: HTTP for Humans.