Introductie tot API's in Python
Chris Ramakers
Engineering manager


JSON

import json
album = {'id': 42, 'title':"Back in Black"}
string = json.dumps(album) # Encodeert een Python-object naar een JSON-string
album = json.loads(string) # Decodeert een JSON-string naar een Python-object
# GET-request zonder headers
response = requests.get('http://api.music-catalog.com/lyrics')
print(response.text)
N' I never miss Cause I'm a problem child - AC/DC, Problem Child
# GET-request met een Accept-header response = requests.get('http://api.music-catalog.com/lyrics', headers={'accept': 'application/json'}) # Print de JSON-tekst print(response.text)# Decodeer naar een Python-object data = response.json() print(data['artist'])
{'artist': 'AC/DC', 'lyric': "N' I never miss Cause I'm a problem child", 'track': 'Problem Child'}AC/DC
import requests
playlist = {"name": "Road trip", "genre":"rock", "private":"true"}
# Voeg de afspeellijst toe via het `json`-argument
response = requests.post("http://api.music-catalog.com/playlists", json=playlist)
# Haal het request-object op
request = response.request
# Print de content-type header van het request
print(request.headers['content-type'])
application/json
Introductie tot API's in Python