נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
PythonPython

APIs עם requestsAPIs with requests

מפגש 22: HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת.Session 22: HTTP, GET, status codes, JSON from the web and handling network errors.

מה נעשה היוםToday's plan

  • APIAPI
  • סטטוסStatus
  • פרמטריםParams
  • תקלותFailures
  • POSTPOST
  • מבנהStructure
נושאTopic 1

APIAPI

מה זה API?What is an API?

  • דף לבני אדם, API לתוכנותPages for people, APIs for programs
  • בקשה → תשובה עם קוד וגוףRequest → reply with a code and a body
  • requests מדבר HTTP בשבילנוrequests speaks HTTP for us

אנלוגיהAnalogy

API הוא כמו חלון הזמנות במסעדה: לא נכנסים למטבח. מוסרים הזמנה בפורמט שהם מבינים, ומקבלים מנה מוכנה.An API is like a restaurant's order window: you don't walk into the kitchen. You hand in an order in the format they understand, and get a finished dish.

טעות נפוצהCommon mistake

first_api.py
import requests_html_typo
מה Python עונהWhat Python says
ModuleNotFoundError: No module named 'requests_html_typo'
ModuleNotFoundError: No module named 'requests_html_typo': כש-import requests נכשל כך, מפעילים את ה-venv ומריצים pip install requests.ModuleNotFoundError: No module named 'requests_html_typo': when import requests fails like this, activate the venv and run pip install requests.
נושאTopic 2

סטטוסStatus

קודי סטטוסStatus codes

  • 200 הצליח, 404 לא נמצא, 500 תקלה אצלם200 OK, 404 not found, 500 their problem
  • r.ok = True לכל 2xxr.ok = True for any 2xx
  • r.raise_for_status() הופך כישלון לחריגהr.raise_for_status() turns failure into an exception

אנלוגיהAnalogy

קוד סטטוס הוא כמו הצליל של כספומט: צליל אחד "הכול טוב", צליל אחר "הכרטיס לא תקין", ואחר "המכשיר מקולקל".A status code is like an ATM's beep: one beep "all good", another "card invalid", another "machine broken".
נושאTopic 3

פרמטריםParams

פרמטרים בכתובתQuery parameters

  • params={"q": "dune"} במקום לבנות מחרוזתparams={"q": "dune"} instead of building a string
  • requests מקודד רווחים ותווים מיוחדיםrequests encodes spaces and special characters
  • r.url מראה את הכתובת הסופיתr.url shows the final address

אנלוגיהAnalogy

params הוא כמו טופס הזמנה עם שדות: במקום לכתוב הכול בשורה אחת ולקוות שיבינו, ממלאים כל שדה במקום שלו.params is like an order form with fields: instead of writing everything on one line and hoping, you fill each field in its place.

טעות נפוצהCommon mistake

search.py
doc = {"title": "Untitled draft"}
print(doc["first_publish_year"])
מה Python עונהWhat Python says
KeyError: 'first_publish_year'
KeyError: 'first_publish_year': ב-API אמיתי לא לכל רשומה יש כל שדה. משתמשים ב-doc.get("first_publish_year", "?").KeyError: 'first_publish_year': in a real API not every record has every field. Use doc.get("first_publish_year", "?").
נושאTopic 4

תקלותFailures

timeout ותקלות רשתTimeouts and network failures

  • תמיד timeout=Always timeout=
  • requests.exceptions.RequestException תופסת הכולrequests.exceptions.RequestException catches them all
  • הודעה ברורה במקום קריסהA clear message instead of a crash

אנלוגיהAnalogy

timeout הוא כמו לחכות לחבר בבית קפה: אחרי חצי שעה מתקשרים או הולכים, ולא יושבים שם עד הסגירה.A timeout is like waiting for a friend at a café: after half an hour you call or leave, rather than sitting there until closing.
נושאTopic 5

POSTPOST

לשלוח נתונים: POSTSending data: POST

  • GET מבקש, POST שולחGET asks, POST sends
  • requests.post(url, json={...})requests.post(url, json={...})
  • מפתחות API בכותרות, לא בקודAPI keys in headers, not in code

אנלוגיהAnalogy

GET הוא כמו לשאול ספרנית "יש לכם את דיונה?", ו-POST הוא כמו למסור לה טופס המלצה שיתויק.GET is like asking the librarian "do you have Dune?", and POST is like handing her a recommendation form to file.
נושאTopic 6

מבנהStructure

להפריד הבאה מעיבודSeparate fetching from processing

  • פונקציה אחת מביאה, אחרת מעבדתOne function fetches, another processes
  • את העיבוד אפשר לבדוק בלי רשתProcessing can be tested without a network
  • cache: לא שואלים פעמייםCache: don't ask twice

אנלוגיהAnalogy

להפריד הבאה מעיבוד זה כמו להפריד בין קניות לבישול: אפשר לתרגל בישול עם מצרכים שכבר בבית, בלי לרוץ לסופר בכל פעם.Separating fetching from processing is like separating shopping from cooking: you can practise cooking with ingredients already at home, without running to the store each time.

דף לבני אדם, API לתוכנותPages for people, APIs for programs

בקשה → תשובה עם קוד וגוףRequest → reply with a code and a body

requests מדבר HTTP בשבילנוrequests speaks HTTP for us

200 הצליח, 404 לא נמצא, 500 תקלה אצלם200 OK, 404 not found, 500 their problem

r.ok = True לכל 2xxr.ok = True for any 2xx

r.raise_for_status() הופך כישלון לחריגהr.raise_for_status() turns failure into an exception

params={"q": "dune"} במקום לבנות מחרוזתparams={"q": "dune"} instead of building a string

requests מקודד רווחים ותווים מיוחדיםrequests encodes spaces and special characters

r.url מראה את הכתובת הסופיתr.url shows the final address

תמיד timeout=Always timeout=

requests.exceptions.RequestException תופסת הכולrequests.exceptions.RequestException catches them all

הודעה ברורה במקום קריסהA clear message instead of a crash

GET מבקש, POST שולחGET asks, POST sends

requests.post(url, json={...})requests.post(url, json={...})

מפתחות API בכותרות, לא בקודAPI keys in headers, not in code

פונקציה אחת מביאה, אחרת מעבדתOne function fetches, another processes

מה למדנוWhat we learned

  • דף לבני אדם, API לתוכנותPages for people, APIs for programs
  • 200 הצליח, 404 לא נמצא, 500 תקלה אצלם200 OK, 404 not found, 500 their problem
  • params={"q": "dune"} במקום לבנות מחרוזתparams={"q": "dune"} instead of building a string
  • תמיד timeout=Always timeout=
  • GET מבקש, POST שולחGET asks, POST sends
  • פונקציה אחת מביאה, אחרת מעבדתOne function fetches, another processes

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich