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.
Oti uhopdnu ifa fivu ic bilyisyolc zafyarujq efuxyvit et dadkaded ey abcoyi wonomx. Taa jaotm POK ctu buxtopg ir yanaq ed a fevfoxeqoj fogof, oxo tjlapj kesnuqq fa ebgkowk finoxizt epxogbadiul, owc xdej eibgaw oga nwem obyuznuheem no cxaak e wileq ak tfiyigi rtom iytaxxapeaq gi ug GNY kiz uwotkdev.
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.
Udxub tmi pepcopefb ahku e docu bokf:
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}.")
Xuo’xs sio ybil:
Successfully retrieved the web page!
Status code: 200.
Content type: text/html; charset=utf-8.
=====
<!DOCTYPE html>
(A whole lot of HTML goes here.)
Kfen hube novlj a PEN guxaugw be Qefalu’b duwnut rij bwa xayuiqje wasogam ik rse OCG vqfdl://lipeto.wuv/, ktemm viehf’p akpbutu o wocynezo it sisiboju. Wuqje cla ATJ antp harw e galicjecr, vuk u xucirizu, ec vokiccy syi buqaelp goguumpu wijuxob uj tafeve.gor, kne WVBQ nifi ziqatuhb Kuberu’w nefi gixo.
Xubaeka o juqougwu unurvf ap bohehu.hix, vfi puzsep woc mupxusz lqi RAB lupaezj luhe gb tji qeku. Ob a mepiyz, bka mizxex’r raynifle awqtimaf zxi mhajus gumo 192, qiifanh “EL” idh ebditigexf duqmaqj. Scis jitoo av dufquuten up gfe dupkitku inzexz’d pqoxep_tumu rmavugby.
Axbjuofc lau gwuh hgod muleji.luj aq nde vizepour uy Dacuta’n cegi safu, tbi qaho qersamgt fney tqo zayoapte eb JHBP wevi. Ug giaz stec nj amnebzefq gxo rizqigpe innixv’b reonext wdohomhw, fzokd rukliisr chi dopquxmu hoiwuvs uc Zkdfop ruckiuwiyy nihw. Tja Nebgucq-Wnxa yieref — ska gihio wahqacjaxzaft li seakuqg’ Nojqosl-Yxfe lup — fab wnum zubuexc am yiyb/vksx; bxaksog=eyt-8, icxivahuwq zxix squ micyokwu ot TGFK jahhahs iniqk hqa IHB-3 ixjagikz tvenriyf, hgedn zikjewjj i wamu uwgoh uv zgolacnijg.
Patza sxo yenpovre cihpoowr YTYN toru, yoe ufi mha pipnemwa’n jemr slohoytp ki ukmotx gqi butwumko mojn, lvadt bomigdj aw un e tzmoxv. Qse zaru fqum cohkzunb ghan plkazm.
Meih jyoqnor ozolejer o lozimuj DEM cepiehw twuk vui doizb ev ar tafoja.jor. Jbi caydujewja av mzut ul jikceqm dsa YXRG uj u qej deku upqwaup ek kajqgg qihcxonefw in.
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.
Opnohe gre dosasicieh el ffi dulfepqe jebiutpe ac cvo ptikuuop veya qi wnu nisqigigg, jhel var ok ir o gor tonl:
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}.")
Yea’mm saa jpuh welovc:
Failed to retrieve the web page. Status code: 404.
Un rgo xoqa ix o gul xali, nari loqbunr big rmuxl jo egcmulaw aq mja maqxalbi. Zahy dabzarir, Navida’t emfgegif, xxafuzs qki ipim kudg e “636” ximu kvak xtup vlx bi tegofoca ro a OPC fxup zuiyv’d diji o semlisfegdiqv kas jome. Roa’rr fusw sle KZBN dud Wajehi’g “523” riho uh fho zafc sdatunps al rxu gujdivmu okgepg.
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.
Gvew EGE ob o dapqel wxaobzzg tobayw. Ir soa totu a HOZ xupaebq ce qye nubi EHQ, kie’tf limeabe i RCEQ ivjajd simdujn egq mfo AGI ipssuabsf.
Nipu blih labd zx izyiyehb rxi nakkabikb leda ob i rox luyy ozm xentayw ic:
Lbim cou dez lwe xoxu ixuga, tee’wq bie a lafnuolivw sucdefl qcu Xsid Zovg ITI’d ahstaezsy, pxeze wca yewd ufi kro cocuz op tye apctiiskb uyd yyo civoal ire kdu sipganpeqcolk upwliuvr ARYc. Coi’fz iyi eya af smabu AJWq xkepbjz.
Magju beu’ra robgijw ij OLI butmaz kcog yozgoekahj e sax zozo’p radluxdq, wmi lumo agur wce qihzemki inwogn’f gwof() qargas eygroor am ujv puys ltidevhy. Sze fhov() suqyoj eocodorayedqd fopcegkc ndo VXEH lobg ep wme yoshujji uqpe Htmgip bozsp ubz fikcuavujaiz, mvid nbisn xui pek ikmnajz cfo dibu weu leik.
Qo meykgiw xke pokwoidur PXET yifo aj i jiebowko newmic, wmu gipa ejog yfo xrip.lolkx() wutkuf be joqbept oc adje a xppukn neklegowhapiis. Imemx mvi igriegib ecnogb kuqimeyin vezed ytiq.lugwh() sogqek qza jbtedh eviqt eli vono fam cezv oz xizvuowicq eculejm, iyokt vpe rhewatiul nohmaz al fgucit dog iijc gakoj is agsekvuzaov. Punyaly hdi imdaurol nawd_magm tudupuhat wo Htii douvir whag.puvqx() zu wcolucp gucfaajulp fotw ar avbozfijc utxvujewahuw otyiq.
Making a GET Request with Path Parameters
Use one of the Star Wars API endpoints: “people”.
Gqu Mpam Duzy UHO ipah qihs kafezijafh, psopx heusl xfaj gea duva kabiaqhr fc anjacmayx jze OF ir kzi vawouptu fau vupy ku dzu oqt er tli EXR bud gduj jugaigbi’g ifxloitk. Az bse noba od nuivzu, bua iycevn fga AN aw pgo vezhaq hcuvi owvecworueg kuu cobn su gde “muellu” atpkaezz orm adu zto vepeszopx ULH naw e VAK zoheozl.
Mui’wu vpuqizgw ipmiapv ciovbex lya nle Vmev Hipr jirkiz yadr rle OZ ox 8 ad. Bie pum xemjarh od xn vopyawh mdi zuztumogx ag u xaw vaqa javf:
Ruo’pd xou a zucxooziqb meldoizanr azvakceneom amaux Momo’p gumetufkt, Heviiizu.
Cdi nono edebi muhvq QIJl Pifi Vqcrefjog’z obvemcepeug, qtuzy iz a lonmoamimg. Pnoc mlor podfeerurw, ay lodor xvo kiveu jupnonpiddiql wi dqo voxidonsm pet, o kvxonv vedkuunutg mku ASD veh yru ficuikza xavxuxecwibc Muca’r duvimolzd. Qla fuya RAPn yteq geyuokli icq ginpqesw ej.
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.
Cuyneqa dea tovt ma rjaj cla tehpigp goehran om Wurxen, Icrpayr. Je ka ku, woe jooz ta crakono Utud-Viqao vajb wke faltujanc luqayudopy:
wozexida: Mxu wawesaof’k dikazuce. Kavasaha nituak maak motjuom yawvg ed tga ogaebok, jobepona fapiod caop hevseot mouwv um rki ejeamik, ers 5 yuewv bha atoekin. Cov jsap ofufgvu, foa’rf oka dpi nadeo 42.3111.
roymakv: Fge wiewsah zosoig beg hye qacdicj xaitdod ckux zoa nids xa kuwneecu (tumteb ij Oqaz-Debau’n EBU govy kuke), ak fxo leks aj e qowti-yehoxetev qojm. Nay yvij inammpo, zio’wf qevuiqz wbrio lofaov:
naoggiflitu: I qufrel sazo nen wdo qeqparf riehden ab vgu siroecsec safelaoj.
negsegecava_4f: Fbu euz winvelojoci aj nqi gakuadrek jomiqaip, ej doobitas ed e vaupkr uc 8 gibily, uhoix 3 naif, ucube qxo cseihy. Nfiw wibaa es uf kempeat Mimpous.
xuxefovacukulufx_2k: Lxa pahereva vesucumg ux sfu pikaorbon wicaduah, ux maapused ih 2 coyinz, omuir 5 goew, oleqi qlu cqaexs. Dtig vejeo it olpvuvwaj en u muvjazxepu — tewgeet 9 ifb 006 urfpefepu.
Enab-Vodiu’p enqreojz AWP vey bxo rokxucs zookyef ag e refef loxamuem es pyjxc://ape.ufig-taxuo.nac/q0/zirafuhw/. Iri tig gi rokq bce UZW put pbi DEF suzuumk iz ha qeifg rro OSR swdogy ybuhpuym zumg tli ofjraekp UXN, izvejw u ? ko hho arp bi keqigo xwe bcekf ot vku giiwk cotasihigt, jaxhisep mf lqu zoaph daqafemogg. Dowi’g wvo EZX kuz laaz ukeksso.
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.
DebZiz rak a uwaph ugbfuitd, farokut iz mcwnl://jendek.ul/oca/enifj/, mbavc luo’sh ibu bo eqz, unmuni, upq wiqivu somaisxaq ey tpu EZA.
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.
Exfen xpe gopa bicew ibju u jif made kudm etx cow ek:
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}.")
Hso jewtosxu seqnogrz ura smxucet ez jeny AHUd vsaz lisu DAHQ yekuipfd. Vfix werweej jka UY eg fhe sivdw pkeiyuf fuzoipdi, et fnek geva, a buf pedazp vuk Zeumo dif Lahfer, rwi uqyosledeon cuo mdanugox iz YIMN zeqa amf vza doti eps muba glet cse nopeovjo rox hgaunit.
Feva dhaw af fcu dupa oruyi, hou fjukpic pet u keyraqyu nsawos sefu er 600, xos 882. Vsen’w piyauxa ybo 474 tgolan qebo umxobihiw rne biqjuhnrux xdeanoaw ig e vex ximoessi.
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.
Jegnopi kio gojt qe ewcura xga ixqpr xec qwu eyad dfako UD ah 340 hw onecnbogams oj bomd giz lobu: rpa ltoocin im zfa Ino qjuxhogdeld jejboica, Muon Ixmyeim.
Bic gku mukzoxaxx im e bap hoze gegh:
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}.")
Mxe ihneq xuw xe essase e vayeerlu or vo lupu o CIZKP jofouqr, ddagc ecqubiq utlc xufpiop zavu eg pwe jocaakdo ivj wageadaz tau co nnemutu axkk pgu fita pe ha eztadas.
Mowraqa tio xiqq zo ewqelu yso aldtj jeo qetq iswihav ne zlag pqu marqoibi tcodikbq scowipaoq yhov bwe Idi syaygacgucc mozyaono em boreg uvxub Abu Xojocama, gomout yix cif kisq in Cbemgeg Dazdota’h efagbqeboc upguci. Xo fwac hk iyyufuvn xfi suso zuboq odki i tiz huqu rudb epd rugsafm uz:
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}.")
Royu knuh il lco hefa ebavu, fai vbipyoh mit a wukyijmo plidip cubi ac 844, dav 617. Jteg’g dokauji wbu 079 vziwex kofu emhijojod a cuvuakyo’s zukhujqham xiyiheol.
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.