Publishers API Guide

This section documents Data.Gov.sa APIs, for publishers who want to write code that interacts with Data.gov.sa and their data.

Authentication and API keys

Some API functions require authorization. The API uses the same authorization functions and configuration as the web interface, so if a user is authorized to do something in the web interface they’ll be authorized to do it via the API as well.

When calling an API function that requires authorization, you must authenticate yourself by providing your API key with your HTTP request. To find your API key, login to the http://data.gov.sa site using its web interface and visit your user profile page.

To provide your API key in an HTTP request, include it in either an Authorization or X-API-Key header. (The name of the HTTP header can be configured with the apikey_header_name option in your configuration file.)

request = urllib2.Request('https://data.gov.sa/api/3/action/dashboard_activity_list')
request.add_header('Authorization', 'XXX')
response_dict = json.loads(urllib2.urlopen(request, '{}').read())

For example, using the Data.Gov.sa API you can:

Importing datasets using APIs

You can add datasets using web interface, but when importing many datasets its usually more efficient to automate the process in some way. In this example, we will show you how to use the API to write a Python script to import datasets into data.gov.sa.

Example

Make this script more interesting (eg. read data from a CSV file), and all put the script in a .py file somewhere with tests and import it here.

#!/usr/bin/env python;

import urllib2

import urllib

import json

import pprint

# Put the details of the dataset we're going to create into a dict.

dataset_dict = {

'name': 'my_dataset_name',

'notes': 'A long description of my dataset',

'owner_org': 'org_id_or_name'

}

# Use the json module to dump the dictionary to a string for posting.

data_string = urllib.quote(json.dumps(dataset_dict))

# We'll use the package_create function to create a new dataset.

request = urllib2.Request(

'https://www.data.gov.sa/api/action/package_create')

# Creating a dataset requires an authorization header.

# Replace *** with your API key, from your user account on the http://data.gov.sa site

# that you're creating the dataset on.

request.add_header('Authorization', '***')

# Make the HTTP request.

response = urllib2.urlopen(request, data_string)

assert response.code == 200

# Use the json module to load the response into a dictionary.

response_dict = json.loads(response.read())

assert response_dict['success'] is True

# package_create returns the created package as its result.

created_package = response_dict['result']

pprint(created_package)

vote: 
Average: 2 (5 votes)

Comments