Bekerja dengan data terstruktur

Pengantar API di Python

Chris Ramakers

Engineering manager

Struktur data kompleks

Respons API Lirik

Respons API lirik dengan HTTP 200 OK. Header: Content-Type: plain/text, Content-Language: en-US, Last-Modified: Wed, 21 Oct 2023. Body: lirik dari "Problem Child" oleh AC/DC.

Respons API Album

Respons API album dengan HTTP 200 OK. Header menyatakan konten JSON. Body memuat detail album "Back in Black" oleh AC/DC, berisi daftar judul lagu.

Pengantar API di Python

Struktur data kompleks: JSON

  • JSON
    • JavaScript Object Notation
    • Didukung luas
    • Mudah dibaca manusia & diproses mesin
  • Content-type, mime-type, atau media-type
  • Format lain
    • XML
    • CSV
    • YAML

Respons API Album

Respons API album dengan HTTP 200 OK. Header menyatakan konten JSON. Body memuat detail album "Back in Black" oleh AC/DC, berisi daftar judul lagu.

Pengantar API di Python

Dari Python ke JSON dan kembali

  Representasi visual pengodean dan penguraian teks berformat JSON dengan Python. JSON memuat detail album "Back in Black" oleh AC/DC.

import json
album =  {'id': 42, 'title':"Back in Black"}
string = json.dumps(album) # Encodes a python object to a JSON string
album = json.loads(string) # Decodes a JSON string to a Python object
Pengantar API di Python

Meminta data JSON

# GET request without 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 with an accept header
response = requests.get('http://api.music-catalog.com/lyrics', headers={'accept': 'application/json'})

# Print the JSON text
print(response.text)

# Decode into a 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
Pengantar API di Python

Mengirim data JSON

import requests
playlist = {"name": "Road trip", "genre":"rock", "private":"true"}

# Add the playlist using via the `json` argument 
response = requests.post("http://api.music-catalog.com/playlists", json=playlist)
# Get the request object
request = response.request

# Print the request content-type header
print(request.headers['content-type'])
application/json
Pengantar API di Python

Ayo berlatih!

Pengantar API di Python

Preparing Video For Download...