#!/usr/bin/env python # coding: utf-8 # # Making requests with Python # # To make a request, you'll need to specify the server and extension, using the requests module. # In[ ]: import requests, sys server = "http://rest.ensembl.org" ext = "/lookup/id/ENSG00000157764" r = requests.get(server+ext, headers={ "Content-Type" : "application/json"}) print (r) # Never assume that your request has worked. If it doesn't work, you should check the response code. # In[ ]: import requests, sys server = "http://rest.ensembl.org" ext = "/lookup/id/ENSG00000157764" r = requests.get(server+ext, headers={ "Content-Type" : "application/json"}) if not r.ok: r.raise_for_status() # If you get responses in json (recommended), you can then decode them. I've also imported the pretty print (pprint) module from python, which makes my json easy to read. You'll find this useful during the exercises to see how the json looks. # In[ ]: import requests, sys, json from pprint import pprint server = "http://rest.ensembl.org" ext = "/lookup/id/ENSG00000157764" r = requests.get(server+ext, headers={ "Content-Type" : "application/json"}) if not r.ok: r.raise_for_status() decoded = r.json() pprint (decoded) # The helper function allows you to call the request, check the status and decode the json in a single line in your script. If you're using lots of REST calls in your script, creating the function at the beginning of your script will save you a lot of time. # In[ ]: import requests, sys, json from pprint import pprint def fetch_endpoint(server, request, content_type): r = requests.get(server+request, headers={ "Content-Type" : content_type}) if not r.ok: r.raise_for_status() sys.exit() if content_type == 'application/json': return r.json() else: return r.text server = "http://rest.ensembl.org/" ext = "lookup/id/ENSG00000157764?" con = "application/json" get_gene = fetch_endpoint(server, ext, con) pprint (get_gene) # ## Exercises 2 # # 1. Write a script to **lookup** the gene called *ESPN* in human and print the results in json. # In[ ]: # Exercise 2.1 # [Next page: Exercises 2 – answers](2_Making_requests_with_python_answers.ipynb)