<jupyter_start><jupyter_text>Interacting with histories in Galaxy API========================================We are going to use the [requests](http://python-requests.org/) Python library to communicate via HTTP with the Galaxy server. To start, let's define the connection parameters.**You need to insert the API key for your Galaxy server in the cell below**: 1. Open the Galaxy server in another browser tab2. Click on "User" on the top menu, then "Preferences"3. Click on "Manage API key"4. Generate an API key if needed, then copy the alphanumeric string and paste it as the value of the `api_key` variable below.<jupyter_code>from __future__ import print_function

import json

import requests
from six.moves.urllib.parse import urljoin

server = 'https://usegalaxy.org/'
api_key = ''
base_url = urljoin(server, 'api')
base_url<jupyter_output><empty_output><jupyter_text>We now make a GET request to retrieve all histories owned by a user:<jupyter_code>params = {'key': api_key}
r = requests.get(base_url + '/histories', params)
print(r.text)
hists = r.json()
hists<jupyter_output>[{"name": "New history", "tags": [], "deleted": false, "purged": false, "annotation": null, "url": "/api/histories/effec70bec8ba12c", "published": false, "model_class": "History", "id": "effec70bec8ba12c"}, {"name": "Unnamed history", "tags": [], "deleted": false, "purged": false, "annotation": null, "url": "/api/histories/49e446c3d6585583", "published": false, "model_class": "History", "id": "49e446c3d6585583"}]<jupyter_text>As you can see, GET requests in Galaxy API return JSON strings, which need to be **deserialized** into Python data structures. In particular, GETting a resource collection returns a list of dictionaries.Each dictionary returned when GETting a resource collection gives basic info about a resource, e.g. for a history you have:- `id`: the unique **identifier** of the history, needed for all specific requests about this resource- `name`: the name of this history as given by the user- `deleted`: whether the history has been deleted- `url`: the relative URL to get all info about this resource.There is no readily-available filtering capability, but it's not difficult to filter histories **by name**:<jupyter_code>[_ for _ in hists if _['name'] == 'Unnamed history']<jupyter_output><empty_output><jupyter_text>If you are interested in more **details** about a given resource, you just need to append its `id` to the previous collection request, e.g. to the get more info for a history:<jupyter_code>hist0_id = hists[0]['id']
print(hist0_id)
params = {'key': api_key}
r = requests.get(base_url + '/histories/' + hist0_id, params)
r.json()<jupyter_output>effec70bec8ba12c<jupyter_text>As you can see, there are much more entries in the returned dictionary, e.g.:- `create_time`- `size`: total disk space used by the history- `state_ids`: ids of history datasets for each possible state.To get the list of **datasets contained** in a history, simply append `/contents` to the previous resource request.<jupyter_code>params = {'key': api_key}
r = requests.get(base_url + '/histories/' + hist0_id + '/contents', params)
hdas = r.json()
hdas<jupyter_output><empty_output><jupyter_text>The dictionaries returned when GETting the history content give basic info about each dataset, e.g.: `id`, `name`, `deleted`, `state`, `url`...To get the details about a specific dataset, you can use the `datasets` controller:<jupyter_code>hda0_id = hdas[0]['id']
print(hda0_id)
params = {'key': api_key}
r = requests.get(base_url + '/datasets/' + hda0_id, params)
r.json()<jupyter_output><empty_output><jupyter_text>Some of the interesting additional dictionary entries are:- `create_time`- `creating job`: id of the job which created this dataset- `download_url`: URL to download the dataset- `file_ext`: the Galaxy data type of this dataset- `file_size`- `genome_build`: the genome build (dbkey) associated to this dataset.**New resources** are created with POST requests. The uploaded **data needs to be serialized** in a JSON string. For example, to create a new history:<jupyter_code>params = {'key': api_key}
data = {'name': 'New history'}
r = requests.post(base_url + '/histories', data=json.dumps(data), params=params, headers={'Content-Type': 'application/json'})
new_hist = r.json()
new_hist<jupyter_output><empty_output><jupyter_text>The return value of a POST request is a dictionary with detailed info about the created resource.To **update** a resource, make a PUT request, e.g. to change the history name:<jupyter_code>params = {'key': api_key}
data = {'name': 'Updated history'}
r = requests.put(base_url + '/histories/' + new_hist['id'], json.dumps(data), params=params, headers={'Content-Type': 'application/json'})
print(r.status_code)
r.json()<jupyter_output>200<jupyter_text>The return value of a PUT request is usually a dictionary with detailed info about the updated resource.Finally to **delete** a resource, make a DELETE request, e.g.:<jupyter_code>params = {'key': api_key}
r = requests.delete(base_url + '/histories/' + new_hist['id'], params=params)
print(r.status_code)<jupyter_output>200
{'fraction_non_alphanumeric': 0.12937267930427984, 'fraction_numerical': 0.01172562048075044, 'mean_word_length': 6.020576131687243, 'pattern_counts': {'":': 18, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '336594', 'license': 'MIT', 'n_tokens_mistral': 1589, 'n_tokens_neox': 1544, 'n_words': 584, 'path': 'galaxy_api_histories.ipynb', 'repo_name': 'mvdbeek/bioblend-tutorial', 'size': '5117'}