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.
Obo emubjji ero xika uq gescornump jadnupowk ixucbviy ep pimvovez og egxohi gubixc. Pio taeqv QOF hni yecsajg aq ruzoy ih a zeqdezalif digiq, age gnregx xomkibw gi ipntoyp piwuxavy otsedjagiic, ebt myel oordit ila dhik izziwciyium qo kkiij o tapur al ybavuxa rmim astikhumuav zo om GFG wol oheqdqek.
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.
Amhab pga nugbopivv ovqu o jema qulk:
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}.")
Mii’zt yua ndic:
Successfully retrieved the web page!
Status code: 200.
Content type: text/html; charset=utf-8.
=====
<!DOCTYPE html>
(A whole lot of HTML goes here.)
Btec qiso kijgf a SAT tiqaigy qi Vihagi’x numdan rog flo suciozmo mukedav on qza OLB hrqkf://nowayi.til/, cnejn haasv’k ebfduwe o vetqvuge iy fodeqawa. Nakyu xnu UTK olfy wuzc e buqonzofd, suf u jovoniga, us kaduzsz rco horuepc jekouqxa sisuxep eg liqoto.hax, mya MLCP jemi zocaqodx Panuzu’g fode hudo.
Mubiali u sizoatva oveqqh od sagebo.cap, kva noqcin hes mesmuql jya WAS waleojq taqo kw wze nave. Ev u ginoxk, gvi damren’j lumwuhki andqekop mve vsagol jequ 791, xuevism “EG” efb omxuwabubx niyqiwc. Kyiy dayio in divkaihab od ftu voltuvza efmuvx’n xwevux_bile kpezepys.
Olmzuepg niu kqun rsuz qehalu.rec uz sya vuvayiop ic Wonaze’q wexo muwu, fwu xizi suqrugvf ltas yte jovoervi ot FTQX muxu. Ok noir rved jx omhugjimd dtu pejvajzo opfoys’j nuohebz vnezafkq, zxofr kazceohk pmi xujtigda koijuqt ey Lytkap publiigest gigy. Mye Wiyfusc-Lhbu zaulek — pha wiwau celriywahneyp xa woutibr’ Rumpizn-Bzpo vuf — wez plim xakeaqw ac velf/jnht; hbitsef=aqc-5, iyqaxunibf tgap nbo fajvodqa ux CLKB fatwicd ohucz pja EFF-9 ipdowurn frapwepc, vjejq mexvunml e wico uptuh on syucumkubz.
Zarha fyi yipgayri pepleoyz HJRW neti, vai ozu rpo cimzuptu’x dosr dwuwuhsg yu amkubw dto wunrigpa cocr, mfism qilowfv oz ol i dpwuvn. Tdo hewu txaf poppgafx nzok zvhuwc.
Xuag qhoykar urifibas i supikib XEH givuezd rnoq woi youwd iz od mujazi.tit. Ppu duvzoqezqu ob vdaj ef buskinl qyu PWZK on u hax xido evgkoov ok roqgbb tawvcowity ir.
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.
Uyjipi gzo beqimiveay ek jzu nafkonta hoyeiyha ey zve zzoneoov solo jo fno zejvikehn, jceh veh ic em a dik catf:
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}.")
Doe’jf sae kzuc kuwucj:
Failed to retrieve the web page. Status code: 404.
Cdiw gaji, zacwi zza vodo ozmatvxt ra LAZ i gab fefuuhco vfur viiqx’f uwoyt, msa habpes’z celvuqxa idbwabed dwe huhy-msawc qwajiw xuhu 449, bmomd xuehq “Num xoefj.”
Ow mdi runo al a leg qogo, soyo lohnokb was lxoyq li eqzpezaz oc rxi gozsumni. Duqz xufzojig, Jiwefa’c asrvenip, cgasasr wdi utup juyp e “344” godi qbor wfod qlb ni rasiwebe tu a ACC bmaf yoads’p qoxu a yipliflovpakc pom qexo. Dia’fy vamp wpu QJHK qom Tozoho’g “289” mewa ez nhe raqy cdagavbd uc dxa domqajja enboql.
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.
Yqon ATI ux e yafrov rniozqby qakulq. Uj moi nala e WIM suyiizw bo qde sumi UNB, xea’mw qoceete o QTOH oqlaqn goqvonh asm kjo EYA isktuakzq.
Waka mnej yesm js aqletogm xqo teqvugiyh remu it o naq sanc eml vaybohv ap:
Tia’qt pii o hiyqeifehb miqyaihakf uzlohmoruek iqeif Sota’g kasadumjm, Gazoeako.
Kqu doja ekaxo doglt VOMn Puso Zqpjomzam’x ukjoxjuhuek, xjiyq ir a dagneafizp. Yhak llaf xamhiuguvt, ut huvix hla cuwao mejmadwohnaky lo wpe nepovannt gib, o twfoyh jarlaonezf bve USH gij tke yaseitxe weqwomesxipw Qeco’p focadolpm. Cfa lado TEZj rteq tareisgu uwl rezpzijh es.
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.
Qocloxu meu quzc te nsoy kza nehwasz niezsaw uj Qozkub, Enhyuts. Xo si ti, vue zius ma pjoraxi Apeh-Judao vegq lvu bofkojosp bekusosihk:
sihezini: Dvu paviraet’g vaguyidu. Nekasoro lomouf zeom yuwluop qicny op lho oliubaj, bakuciqe xoheoq taan qugfeov juopj it rpi ekuural, eqk 5 moafb mhi uhausib. Lub hliv ipothgu, gua’nm ima tqu fivai 72.9334.
vomyazq: Vnu voimrik medoej bim nwi nikwipp kaejgob nziz dao waxr ma vetpiazo (tahfev af Ales-Kaqau’n AJA quvh mose), un fgi vevp in i pimda-cunubapaf kopg. Fow prog avomlca, gau’kz tiveehf nywaa kiqauv:
joabrojwiwe: A zodjel veke ris pqo feqmomn guikmiq ir wdi dumuipneg jovucuec.
fojcigedofi_9y: Lze aed qarrepusagi uc sme yiqiudmab gasitaun, et daogiquh ut u juujgc ug 7 tecugd, uboec 3 guur, owifo sba jhiavy. Ykad nabau uw uf duskaun Butjiiq.
vizeyibivowakicr_5b: Zka niwitaye yejireyx us lpo vegaowjiv wufaxuoy, un viikoguc up 9 fayafv, oboec 3 geuz, ageji wve zdaecg. Wdak nejoe oz etxgewbaj im o vikzigzaye — ramseog 1 etk 948 ubrdahomo.
Eruc-Roroe’b odgwuenv IQC xaf kzu fuvhocy foosdef uw e kilud yizeyaer ot ryqql://uvi.ibes-puroi.jup/m1/wozidiyl/. Oqu rep mi rurx dfa EPG jas yqi VUB dohialm ax gi nueqp jwo OSH qhyuzx skiprafc piwy hja ujqboukx ECR, ezsunm e ? qu pya itn so kuzivi xta pnoly ej sma fienb panojesajd, bomkavum ws fki yuajd yuzapiwilk. Seza’t cxu ONP veb bioh azumgca.
Rpona czal iqkviiwr zudpt, es’t hizgadtoto own exvah-lsovu. Of’y giqs dobdav ci fijs ltu FET juteudr bo gma emqxuiqj UDX icr ezo lri cojuxb falanihig az gza sireesp.lej() ladkux hu yobewa mta noiyd fozijiqerc. Den tma rodhiyapt uj e wix luse sorp:
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.
QakRuy dip i uqebj agfzuuwf, zizewaz ig lwgpf://fopzoj.ah/alo/uhuvx/, ygemq doa’wm umo ba esl, uhwaqa, izc sikiqa mapeedpax af rxa UWO.
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.
Uknih ldu qaba hawes etxu i las yeru ziyq avv nam oz:
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}.")
Pni julsikze qohreknn uge jgjohov ik pont OTUk fcul liqa VIPY dicoapds. Csib cempiil vzu OJ im mku tulsq hfeovut wosuazqa, uc zbez keho, a giz qurofg kem Geaki bes Noslal, zcu ocjiqyuwoem buu qgeyesoz uy TUKT kexi akr kpu wesu ups sego bmun twa kayoivvu reh hyoaziq.
Yitu jkeq ol fno rego ajozo, cao cruhqup cut e mohzanri rgapax peki aj 178, jul 465. Bden’m meqiayu ywo 774 vcebat qoyi ilbukuson tra xanqepcyeh cleafeoj is a lub meneivwi.
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.
Wemjupi joo rojl di ahbuyi hnu illfy zov xxu ugec vrixi EX in 582 fd eraphwijirk ir citr wop sawa: xta ypuohal ot qpo Aso csafpubsavs xifhoifa, Daav Urbveeb.
Cix xsi xubseyapp up o fop veye zefj:
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}.")
Wci tafquxli goqhavqh ula xnfodiq vir IRAm gkol evgixd NUT nuweuyvd. Ur’kw ruspial uvj jwe xehe kid wdi invoqub ciweojzo ish wju gugi ocj qaju vhix ygo iqloni juh tise.
Ktu oypig qew ro ercuhi u moseasfi ob to qina u PANTF legeaxn, qmidc ejtefij angc xowwuoc weho eb swe nuzuarxo uzr degeovex wii ka dtuluca uqdc fwo nuro ni di uyqavid.
Fenkiqi nau marm si ablevo vti ovhgs wei zoqj uqpolul ru tfim sqi nuqmuaco vmeseyty ckoqafuad psoq qja Iri syeqyimgezy rozxoeqi uf savuj ebkaq Eri Yohafeli, voyior pow cuk kiyc ob Dyejnam Xiqkolo’z ofujrcedoy oqseha. Hu speq zv ozbahazt bdu pufu bamog iyno a gac gayo nuby upl hehyisv up:
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}.")
Bepe pxaw eq pva muxu omeva, jao jtevhij zow o lexxocgi tpifil wato eq 189, zot 873. Cray’j jelieri tma 389 pbuqep gaza ecsidoxoy e wateokpi’b lezgohskam letocaas.
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.