Header dan kode status

Pengantar API di Python

Chris Ramakers

Engineering Manager

Anatomi pesan request dan response

Contoh pesan request dan response. Request: GET /users/42 dengan header. Response: 200 OK dengan body JSON berisi info pengguna.

Pengantar API di Python

Start-line

Contoh tiga bagian berbeda dari pesan request atau response, dengan start-line disorot

  • Server akan selalu menyertakan kode status numerik pada response
Pengantar API di Python

Kode status

Kategori kode status

  • 1XX: Respons informasional
  • 2XX: Respons berhasil
  • 3XX: Pesan pengalihan
  • 4XX: Kesalahan client
  • 5XX: Kesalahan server

Kode status yang sering dipakai

  • 200: OK
  • 404: Not Found
  • 500: Internal Server Error
1 Untuk daftar lengkap semua kode response, lihat halaman MDN tentang status-codes di https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Pengantar API di Python

Header

Contoh tiga bagian berbeda dari pesan request atau response, dengan header disorot

key1: Value 1
key2: Value 2
Pengantar API di Python

Contoh: Negosiasi konten dengan header

Contoh tiga bagian berbeda dari pesan request atau response, dengan header disorot

  • Client menambahkan header accept: application/json ke request
  • Server merespons dengan header content-type: application/json
Pengantar API di Python

Header dengan requests

# Menambahkan header ke request
response = requests.get(
  'https://api.datacamp.com', 
  headers={'accept':'application/json'}
)
# Membaca header response
response.headers['content-type']
'application/json'
response.headers.get('content-type')
'application/json'
Pengantar API di Python

Kode status dengan requests

# Mengakses kode status
response = requests.get('https://api.datacamp.com/users/12')

response.status_code == 200
True
# Melihat referensi kode status dengan requests.codes
response = requests.get('https://api.datacamp.com/this/is/the/wrong/path')

response.status_code == requests.codes.not_found
True
Pengantar API di Python

Ayo berlatih!

Pengantar API di Python

Preparing Video For Download...