מפגש 22: HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת.Session 22: HTTP, GET, status codes, JSON from the web and handling network errors.
HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת. בסוף המפגש מוסיפים צעד לפרויקט המלווה.HTTP, GET, status codes, JSON from the web and handling network errors. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
APIAPI
סטטוסStatus
פרמטריםParams
תקלותFailures
POSTPOST
מבנהStructure
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושא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
כשאתם פותחים אתר, הדפדפן שולח בקשת HTTP ומקבל דף. API עובד אותו דבר, רק שהתשובה מיועדת לתוכנות: נתונים נקיים ב-JSON. ספריית requests (התקנתם במפגש 13) שולחת את הבקשה. כאן נשתמש ב-Open Library, ספרייה פתוחה עם API חינמי. שימו לב: הקוד באתר רץ בזמן הבנייה בלי אינטרנט, ולכן תשובות השרת כאן הוקלטו מראש. על המחשב שלכם תקבלו תשובה חיה.When you open a site, the browser sends an HTTP request and gets a page. An API works the same, except the reply is for programs: clean data in JSON. The requests library (installed in session 13) sends the request. Here we use Open Library, an open library with a free API. Note: the code on this site runs at build time without internet, so the server replies here were recorded in advance. On your computer you'll get a live reply.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצה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.
שוכחים להתקין את requests בסביבה הפעילה.Forgetting to install requests in the active environment.
נושא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
לא כל בקשה מצליחה. קוד הסטטוס אומר מה קרה: 2xx הצלחה, 4xx בעיה בבקשה שלנו (כמו ISBN שלא קיים), 5xx תקלה בשרת. בודקים r.ok או קוראים ל-r.raise_for_status(), שזורקת חריגה ברורה כשמשהו נכשל, במקום להמשיך עם נתונים שגויים.Not every request succeeds. The status code says what happened: 2xx success, 4xx a problem with our request (like an ISBN that doesn't exist), 5xx a server fault. Check r.ok or call r.raise_for_status(), which raises a clear exception when something failed, instead of carrying on with bad data.
אנלוגיהAnalogy
קוד סטטוס הוא כמו הצליל של כספומט: צליל אחד "הכול טוב", צליל אחר "הכרטיס לא תקין", ואחר "המכשיר מקולקל".A status code is like an ATM's beep: one beep "all good", another "card invalid", another "machine broken".
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושא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
לחיפוש מעבירים פרמטרים: ?q=dune. אל תבנו את המחרוזת ביד: רווחים, עברית וסימנים כמו & צריכים קידוד. מעבירים מילון ב-params, ו-requests מטפל בכל השאר. r.url מראה את הכתובת שנשלחה בפועל.To search you pass query parameters: ?q=dune. Don't build the string by hand: spaces, Hebrew and symbols like & need encoding. Pass a dict in params, and requests handles the rest. r.url shows the address actually sent.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
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", "?").
ניגשים למפתח שלא קיים בכל תוצאה.Accessing a key that isn't in every result.
נושא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
רשת נופלת, שרתים איטיים, וכתובות משתנות. בלי timeout, התוכנית יכולה לחכות לנצח. עוטפים בקשה ב-try ותופסים requests.exceptions.RequestException, האב של כל שגיאות הרשת, ומחזירים הודעה שהמשתמש מבין.Networks drop, servers are slow, and addresses change. Without a timeout, a program can wait forever. Wrap a request in try and catch requests.exceptions.RequestException, the parent of every network error, and return a message the user understands.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
מפתחות API בכותרות, לא בקודAPI keys in headers, not in code
GET מביא נתונים. POST שולח נתונים לשרת, למשל ביקורת חדשה. json= הופך מילון ל-JSON ושולח אותו. API שדורש הרשאה מקבל מפתח בכותרת (headers); את המפתח שומרים במשתנה סביבה, לא בקוד (זוכרים את .gitignore?). httpbin.org הוא שירות בדיקה שמחזיר את מה ששלחתם:GET fetches data. POST sends data to the server, say a new review. json= turns a dict into JSON and sends it. An API that needs permission receives a key in a header (headers); keep the key in an environment variable, not in code (remember .gitignore?). httpbin.org is a test service that echoes what you sent:
אנלוגיהAnalogy
GET הוא כמו לשאול ספרנית "יש לכם את דיונה?", ו-POST הוא כמו למסור לה טופס המלצה שיתויק.GET is like asking the librarian "do you have Dune?", and POST is like handing her a recommendation form to file.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושא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
טריק של מקצוענים: הפונקציה שמדברת עם הרשת קטנה ככל האפשר, וכל העיבוד (בחירת שדות, ניקוי, חישוב) בפונקציה נפרדת שמקבלת מילון רגיל. כך אפשר לבדוק את העיבוד עם pytest בלי אינטרנט, ובאתר הזה, כל תרגילי המפגש עובדים כך. ומטמון (cache) קטן חוסך בקשות חוזרות.A pro trick: the function that talks to the network is as small as possible, and all processing (picking fields, cleaning, computing) lives in a separate function that takes a plain dict. That way you can test processing with pytest without internet, and on this site, every exercise in this session works that way. A small cache saves repeat requests.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
דף לבני אדם, API לתוכנותPages for people, APIs for programs
מה זה API?What is an API?
בקשה → תשובה עם קוד וגוףRequest → reply with a code and a body
מה זה API?What is an API?
requests מדבר HTTP בשבילנוrequests speaks HTTP for us
מה זה API?What is an API?
200 הצליח, 404 לא נמצא, 500 תקלה אצלם200 OK, 404 not found, 500 their problem
קודי סטטוסStatus codes
r.ok = True לכל 2xxr.ok = True for any 2xx
קודי סטטוסStatus codes
r.raise_for_status() הופך כישלון לחריגהr.raise_for_status() turns failure into an exception
קודי סטטוסStatus codes
params={"q": "dune"} במקום לבנות מחרוזתparams={"q": "dune"} instead of building a string
פרמטרים בכתובתQuery parameters
requests מקודד רווחים ותווים מיוחדיםrequests encodes spaces and special characters
פרמטרים בכתובתQuery parameters
r.url מראה את הכתובת הסופיתr.url shows the final address
פרמטרים בכתובתQuery parameters
תמיד timeout=Always timeout=
timeout ותקלות רשתTimeouts and network failures
requests.exceptions.RequestException תופסת הכולrequests.exceptions.RequestException catches them all
timeout ותקלות רשתTimeouts and network failures
הודעה ברורה במקום קריסהA clear message instead of a crash