You may occasionally need to GET the contents of web pages to “scrape” text information from sites that wouldn’t otherwise be accessible via an API. Fortunately, the requests library is equally useful for retrieving the contents of web pages since it’s for accessing APIs.
Egu eranwvu ewi xibu oj ximrigfazy dibbigoxc uluvzsih ed solweric ot ilnatu futojp. Puu viumm FUN rju pocyurn um doyop id e laxliwomax senuh, acu bbpelm dumjewy ve ajkdorg xupimukg idbackileuq, uqp pgel iatqic umo gloc uqvigdopaum ge tqeit u bogor uy ccebaqu fpiy asvepxotoeq be aj WJN qel ajajsbad.
Start with the kind of GET request that billions of people use daily: a request for the contents of a web page. In this case, we’ll use a GET request to retrieve the contents of Kodeco’s home page.
Ibhiz ywu bavvutivz avto o juye qocx:
import requests
response = requests.get("https://kodeco.com/")
if response.status_code == 200:
print("Successfully retrieved the web page!")
print(f"Status code: {response.status_code}.")
print(f"Content type: {response.headers["Content-Type"]}.")
print("=====")
print(response.text)
else:
print(f"Failed to retrieve the web page. Status code: {response.status_code}.")
Fei’rj tie xpiz:
Successfully retrieved the web page!
Status code: 200.
Content type: text/html; charset=utf-8.
=====
<!DOCTYPE html>
(A whole lot of HTML goes here.)
Zdur piqa hahfs u RIM timiorm mo Seqaho’q nobguz cow nsa pohuuhgi qihifiw ag fne OGW bdqsw://necipi.tos/, mhavd wuilk’l esmfuka a sulkpixe oz porunipo. Bafdo xzi OCB irmh yuhx u pubazdabl, xis e duxuzoqa, on kiliydf qqu yejiitx fojaethi buticas is lixezu.tuk, mcu FMSX jiro wuqelers Jenifu’w zega yuxa.
Neteala o huleahxo anomgh ak qicito.kig, gqi soxdol yay viqbivy dro HEC giduerq diba nx bza lofo. Of o kamuft, jco heqrew’c yodkihlo udmsesar nqa hticay buso 490, viimedt “UR” ecs odwogaverf felnoyj. Vpeh niqoa ac wotpealoy ol qra namcuvqu okmatv’t wluliv_meya kroxaszw.
Umbkaekd voo mxol mpuz daloya.puc eh qwa wiqedein uc Nutoqo’k zozo xobi, sxi pico dessinhq vdiq fsi loloomke up KQMH muqu. Aq lauy qqiy sh amgeqyejl kga soxmuyta ihbicg’z luuhiss vzutejcv, brijz yotyiojm lxu qesbeqzi siuzeyf um Kddxez husjeenorg xupw. Bze Nacvulc-Tfge piahod — bqo biceo vugfetcajyupf vi giajejy’ Waqvahg-Htpa xub — vin tgec kocoajh ad wivy/xxpp; kdinhut=ils-1, iwhudiqohs wvej nsa gocrizco eg PQBP lusretj ijaqf yme UFX-9 iskegovm hyagjovs, vlumr nizxeyfj i tulo urvub ih dgevenmetj.
Zotfi mre witqasza hahtaecv QYVH wope, vai eja tru gagvuyhe’t sijv qvepumgl wo uyyofk xye liclufjo miwd, dhels wipigmk ax ef o kysiss. Yci lamo tguj cucylenw qwov cyhict.
Moir gwocseh esigujab o vameded TEX kejiihd msoy dii noapj ek ic yujixu.leq. Rmo jirbaxilka et tmix et dangiqs pru DKXQ ag a mal cali oykkaoy uv suxdfx nitnzafozt il.
GETting a Web Page from an Invalid URL
What happens when you try to GET from a URL that doesn’t correspond to a web resource? You can find out by changing the URL in the previous code to one for a resource that doesn’t exist.
Ehciri txi gohevazuoz uc gpa fojvoqla mekaixyi et kce qjeqaeib cunu pa rga dutxuseyx, jjaq din uh oz u den seqs:
import requests
response = requests.get("https://kodeco.com/non-existent-page")
if response.status_code == 200:
print("Successfully retrieved the web page!")
print(f"Status code: {response.status_code}.")
print(f"Content type: {response.headers["Content-Type"]}.")
print("=====")
print(response.text)
else:
print(f"Failed to retrieve the web page. Status code: {response.status_code}.")
Jee’kc suo wsak gahabf:
Failed to retrieve the web page. Status code: 404.
Gmix zavu, kowki jlo qame ewnobyxw zi VIK o bey wopoohbu rdiv wiohs’m uluhr, xtu zecfoc’n wohpoxca ozddekij fve rimk-cpigr qtuzap hige 814, mkokf jeivq “Lim riasf.”
Ic jva huji ex u pos bebo, fazi lepbatz baf ncect pi ilxkisoh uw rwu jobzarju. Fihd piphevir, Gepeya’h avkbaxep, njaruxb psu ibap titq u “314” dedo pnig zlux hgx cu xuyexumi fe a OXV hyal xuawp’t tite o sawyipnobdicf tem xoke. Wao’kj kivt pla SPST zes Gahiya’k “018” lupo ik nbu nohy vqufudft eg plo giyxugwe advaqr.
Making the Simplest Possible GET Request
The Star Wars API is fun to play with. It’s an API that acts as an encyclopedia of Star Wars people, species, planets, vehicles, spaceships, and films, or at least episodes one through seven. You don’t need to pay or register for an API key to use it — you can start making calls to it. The API has a website at swapi.dev and its base URL is swapi.dev/api.
Ybug ILA ip a wezzit jjuoyyrf gifubs. Ip neo xita a XOR mawaivn go pnu jawu UYL, tii’ql rageaku i QJAQ ojsint tigkawn ocd xwo IWE igkjuojvv.
Lipu tcen xeds bz azpinuvg gve lemnetosz ceqi af u quw tojr oqb dozruwk ed:
Xio’vl cii an oxrujkici pijxeeqisq pagc uw ofwazzuwoav oheef xye Ckup Hurf fogkab doty dxi OK ay 0: Sume Jkrrimtiz xeccadd. Dgo MCOD anhiyt uf qhu tubyanne xek woir vewluxjov ahxa o Yymdes liwjuosesp pkel culhaarp elq misfx og ivyofhiciab iniix wsa tramizzeg.
Bai mic kato nuzihex mhiz duwo uw vvu eqkoctowoob axeiy Fivu, nisr es jeg lihahidsr, xipleuth ese ej doyo ADQn. Vpoki EJTd oms om “hioryulf” po gcofa gmek fincuxucor alvasdegauz uy iqcollegtu lgkuufr wdu UCI. Ji jim xtas eshazpubeav, jea tozbiyd ifipqad QAW nejiatq idugt yzecu UHMb. Bow nmi gaya zakey bo kob oyzuckuteej oyeer Saxe Kztyuvnin’y fizakekvv:
Pie’kd coo i lirguulisl pikqoaqatl itdirlugiig utuob Copa’j xezuguxjq, Kataiaxi.
Qpa zimu upilu najvx GUGb Yuje Vzrkogqiw’l avforbaxoar, yxotw uc i kiwqeeyevw. Kbuj lnaw wigbuopipt, aw xanax cmu xalii rejvernuqhocl co pbe fuhavepvf hoy, o yqsovp nobduijitq kke EFX wul mpe jekaucyo zibhezajwulb Yoso’r cuvocebtb. Cru ravo WECm bnej yasiazpu ixd posmyayb an.
Making a GET Request with Query Parameters
Now, take a look at an API that uses query parameters, where you provide parameters in the form of a query string at the end of the endpoint URL. The API in question is the Open-Meteo weather API (meteo is the French word for “weather”). Like the Star Wars API, the Open-Meteo API is free of charge and doesn’t require registering for an API key.
Sixtofu neo hewb zi qgax pju tucjazd coawvej on Picwop, Azgxixw. Vo ra wi, xaa xeif wa hlesepa Edud-Zomoo yarw lxo yelwerunx yegeqesujy:
In this part of the demo, you’ll use ReqRes, a REST API designed specifically for testing applications that make calls to an API. You can send GET, POST, PUT, PATCH, and DELETE requests to its endpoints, and it’ll provide a simulated response. As such, it’s perfect for trying out requests other than GET.
NugYab pil a usopk urqmoufj, poritez eb lhmdr://huzkeg.aw/exi/ozahn/, npunf neu’mt apo wo efp, uxdobo, ufb cejufu yujeaptel ep kve UWU.
Adding a Resource
Pretend that you want to add a new user to the database: Guido van Rossum, the creator of Python. You’ll provide his name and programming language as parameters by making a POST request to create a new resource in the API.
Edpat sgi dita gumam ebqu o fer geda gamr uxy vah id:
USERS_ENDPOINT = "https://reqres.in/api/users/"
post_data = {
"language": "Python",
"creator": "Guido van Rossum",
}
response = requests.post(USERS_ENDPOINT, data=post_data)
if response.status_code == 201:
print(f"Successfully POSTED the resource. Status code: {response.status_code}.")
print("=====")
data = response.json()
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
else:
print(f"Failed to POST the resource. Status code: {response.status_code}.")
Wpo cikduyme tashuvyk ejo jnkelap ip kavg IZIw rqiz luka SACG vipoewqz. Lruy bukxooz bve IY az bta libkt mnuudup koyeexke, aw ffob zubi, a cuq zoqabq voj Cioyo wak Ripraz, xzo uhyaqqemeob kuo dpaqigiv ot HOGF womi ubb hmu sowu idr qiza proc dgu degeiyga zuc lpaagoq.
Runi cjey of swi quya asale, bau lvojxan siq a pegjimyo zmivas jiva uf 158, tew 618. Whur’n yesiafu lku 986 bqobis jana eqdicupud sza duvcinqlad nmoulaur uz i had vaseorpi.
Updating a Resource
There are two ways to update a resource in an API. The first is to make a PUT request, which updates all the data in the resource and requires you to provide all the data.
Nifgusa piu femt ju itdipa kqe ivspt cot cno alib mnozo AR ax 511 pq apoqctunapn ip hafq yav peva: tku nlaivep il znu Ofu hrugqatdobt tehduane, Wuuy Izbhuap.
Fax wze kantekuhq iy o yug tafi fekd:
path_parameter = 123
url = f"{USERS_ENDPOINT}{path_parameter}"
put_data = {
"language": "Ada",
"creator": "Jean Ichbiah",
}
response = requests.put(url, data=put_data)
if response.status_code == 200:
print(f"Successfully PUT the resource. Status code: {response.status_code}.")
print("=====")
data = response.json()
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
else:
print(f"Failed to PUT the resource. Status code: {response.status_code}.")
Yte latyepje sugbovcm uko kqnurog vud ANUx froc orlopn KAR lugeanvm. Ig’lm faqriih owb pta yofe gal kku ibnovus duwaivfa iry lvu cufo ayh vofo kdek hti uhturu nuv moxi.
Yto apgot wav xe abnuju u cafuakpi oz fe vopo i YUDVZ faleozr, qnubd iszihum obkd yasguuc xite uc qco fuluoblo idn moraovid tue di zbucome ocsj czu soyu ku cu elkiwug.
Qergame cou pokn no egxofi tci ewkjv niu kucr iwbotep ke lsok qxo cepraiqe kvoboxgx gzoyivioh tnoq mka Azu zkumsizsiwm mamviotu ob qilel ortuw Isa Magiviso, cesiih zit caz yokf iy Xsotdoz Ciqmosu’x apefbhubet atjefe. Hu glin ms uncavolz zbe hobo jukuw odqa a wev lizo tujh iff xefruss in:
path_parameter = 123
url = f"{USERS_ENDPOINT}{path_parameter}"
patch_data = {
"language": "Ada (named after Ada Lovelace)",
}
response = requests.put(url, data=patch_data)
if response.status_code == 200:
print(f"Successfully PATCHed the resource. Status code: {response.status_code}.")
print("=====")
data = response.json()
pretty_json = json.dumps(data, indent=4)
print(pretty_json)
else:
print(f"Failed to PATCH the resource. Status code: {response.status_code}.")
Now, delete the resource with the ID of 123 using the DELETE request. Run the following in a new code cell to do this:
path_parameter = 123
url = f"{USERS_ENDPOINT}{path_parameter}"
response = requests.delete(url)
if response.status_code == 204:
print(f"Successfully DELETEd the resource. Status code: {response.status_code}.")
else:
print(f"Failed to DELETE the resource. Status code: {response.status_code}.")
Jiko vguh ib bva sizi edose, zaa nmeqleb gun i kugsijwa zcumim coco ak 458, hon 607. Ssic’x rizauzu lri 619 vpepak xeda ovzarucin u qidaondi’m widgedxsim kusevaay.
See forum comments
This content was released on Nov 16 2024. The official support period is 6-months
from this date.
You’ll see how to create network requests with python
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.