Son düşünceler

Python ile API'lere Giriş

Chris Ramakers

Engineering Manager

API temelleri

  • API'lerin rolü
  • API türleri
  • URL bileşenleri
  • İstek ve yanıt yapısı
  • HTTP fiilleri

Python ile API'lere Giriş

Python ile API'ler

Requests paketi

import requests

HTTP yöntemleri

# Bir kaynağı oku
requests.get('https://api.my-music.com')
# Kaynak oluştur
requests.post('https://api.my-music.com', data={...})
# Kaynak güncelle
requests.put('https://api.my-music.com', data={...})
# Kaynak sil
requests.delete('https://api.my-music.com')

URL parametreleri

query_params = {'artist': 'Deep Purple'}
requests.get('http://api.my-music.com', params=query_params)

Başlıklar (Headers)

headers = {'accept': 'application/json'}
response = requests.get('http://api.my-music.com', headers=headers)
print(response.headers.get('content-type'))

Durum kodları

response = requests.get('http://api.my-music.com')
print(response.status_code)
Python ile API'lere Giriş

İleri konular

  • Kimlik doğrulama
    • Temel Kimlik Doğrulama
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API anahtarı/jeton ile doğrulama
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • Yapılandırılmış veri
    • JSON biçimli veri isteme
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • JSON biçimli veri gönderme
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Python ile API'lere Giriş

Hata yönetimi

  • Hata türleri
    • Bağlantı hataları
    • HTTP hataları
      • 4XX İstemci hataları
      • 5XX Sunucu hataları
  • Durum kodlarıyla hata yönetimi
    • response.status_code
  • İstisnalarla hata yönetimi
    • raise_for_error()
import requests
from requests.exceptions import ConnectionError, HTTPError

try:
    response = requests.get("http://api.music-catalog.com/albums") 
    response.raise_for_status()

except ConnectionError as conn_err: 
    print(f'Connection Error! {conn_err}.')

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
Python ile API'lere Giriş

Tebrikler!

Python ile API'lere Giriş

Preparing Video For Download...