To make a request, you'll need to specify the server and extension, using the requests module.
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.
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.
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.
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)
# Exercise 2.1