Yapılandırılmış verilerle çalışma

Python ile API'lere Giriş

Chris Ramakers

Engineering manager

Karmaşık veri yapıları

Lyric API yanıtı

HTTP 200 OK ile Lyric API yanıtı. Başlıklar: Content-Type: plain/text, Content-Language: en-US, Last-Modified: Wed, 21 Oct 2023. Gövde: AC/DC'nin "Problem Child" şarkısından sözler.

Albüm API yanıtı

HTTP 200 OK ile Albüm API yanıtı. Başlıklar JSON içeriği belirtir. Gövde, AC/DC'nin "Back in Black" albümü için parça listesini içerir.

Python ile API'lere Giriş

Karmaşık veri yapıları: JSON

  • JSON
    • JavaScript Nesne Gösterimi
    • Yaygın desteklenir
    • İnsan tarafından okunur, makine tarafından kullanılır
  • Content-type, mime-type veya media-type
  • Diğer biçimler
    • XML
    • CSV
    • YAML

Albüm API yanıtı

HTTP 200 OK ile Albüm API yanıtı. Başlıklar JSON içeriği belirtir. Gövde, AC/DC'nin "Back in Black" albümü için parça listesini içerir.

Python ile API'lere Giriş

Python'dan JSON'a ve geri

  Python ile JSON biçimli metnin kodlanıp çözülmesinin görseli. JSON, AC/DC'nin "Back in Black" albüm ayrıntılarını içerir.

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
Python ile API'lere Giriş

JSON veri isteme

# 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
Python ile API'lere Giriş

JSON veri gönderme

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
Python ile API'lere Giriş

Haydi pratik yapalım!

Python ile API'lere Giriş

Preparing Video For Download...