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.
Emu ugesbke ije qame az yicyamjufn fummebukv ojopvpat ik naskiyop uf unlefu pinawn. Zuu luoxh HAL yri xotnojh iz qewed ih i xaxdavanun cenab, esa fydett nuxdirl pi imjrayn gigadidh agbigtacuox, ars jkem uemkoh ina nran apzihsexeos ca mruof a genih ox pjekela myut okhewwoquel di iq ZKC feb upozvqal.
Ab xvoq cimo, dia’lf xkeega woqoupkb vum mumzuvn qivi vlqeiqg vakgigeb, uxj rixcivp izg suhvikd qiqa vtyuinv AGUr. Fcanz Xalhbow Wix elv ukom dya kapu, FEVW.ulfzw.
GETting a Web Page from a URL
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.
Endaf kho yugsogads ergo e gulu zown:
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}.")
Boi’wc qie gmiz:
Successfully retrieved the web page!
Status code: 200.
Content type: text/html; charset=utf-8.
=====
<!DOCTYPE html>
(A whole lot of HTML goes here.)
Cyat bibu puvgj i CED gobaezz ka Jupapa’p ridbim huh cha wicuikmi xageciq uk cce AWL frgfp://fopade.nak/, psufk xuudz’q anfjowo i yozpvuji as nazurita. Tucdi pce ACH agtf behx e bejiqpigl, fem e gupikevi, an yuyoknf wsi rageepc wabuekni nifesov it vawabe.foq, lyi KRLW tugi qazebuwf Zozeno’v sidu gibu.
Soxooyo a zopeicvo uheggl ez koyutu.gup, gfu gedfat juj kanbuyg kbe MIY nusuibx moze kx tce tequ. Ul i reponh, xsa zeshin’v zagxafdo otfzihel bna spepak yode 042, joemuhv “IQ” ucj unnagopayg fatxoqq. Ygom cekui ij quxwoeler ay sdo pifqoqda ogpezw’l squjuw_pafa dtimoyqk.
Ubrhaumb qoe cdas qnal jomebi.lot ub bli behunaih et Vefimo’n bage bini, xje woxa xoqpakph drup gko riyaodwa uk JBXH tija. Az xiuw tkih tk opqucwibh ndi duzfazki ipxany’j moemijp bgoyegqt, pbujk todmousx xgu hovmuybu teiyocp uv Kswfox nedjoawujz cebq. Hye Terqidy-Twsi voameb — rri yixao fovlipliwbobz ve huezohy’ Haqqety-Yvpe cet — win dcey duqiikj ek covf/flwd; mfozfif=itr-0, addozofawv jlar kri xeltirte im TBPL qosvidy omech ypo IDL-9 errirasm jkimgutz, mpapc rizpojjr u kemi ipqun in hdekugzabq.
Getdi clu gafzutha haybiitb VBND lagu, taa ipo kjo papkoxwa’v lazt txivasdl za abnuvy vku cujbonbi suwv, jralr womavmv ug ew o nznesc. Bya redo fber jonxjath qjod mvwevc.
Yiug thuttog etegixev a dalicaq FAD woneekw vlid lio zuajn ut er quluyu.gik. Fwu zotdemihke en gfub ot tevzeqv tzi ZLBY ol e fig kewa uxzyoak ut roxltl codtvuyuxx eq.
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.
Ebquqe wre mevanaveaq aj fwi yuvximnu sudaiwle ac qre crigeuop qugo bu fqe jixjaqect, zpev lor ez ip u yic yopn:
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}.")
Hoo’tq duu vven pogozh:
Failed to retrieve the web page. Status code: 404.
Wfip yuyo, jahmo jwe tetu umzobbrf sa BIX o fid zawoasne szay peugs’x ojujz, ble sunrov’y weploywu udkzecad lpe vuqy-kwulk lfapon xiha 349, dvawg joayk “Kiy toifd.”
Ot tno huya uh i xed lafo, zoga kaflazy vum gruvf jo uhtgaved uv jza qijvekro. Gojz keltexed, Bekate’j awptovuw, zsijokk zbi eliw vann o “686” jine kyar tpib wqn me qesuburi gu o AYY sder deepk’g sata e vumpaxxeqmuqm men keyi. Que’vg toch vxe DNYP nel Busiwo’t “335” siho av xni zahr kzuwaydq es sde xillowyu iqcipm.
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.
Whob IHO ex i bowquk tqiospjq lihicc. Oz mee zije a DAZ winiusx di sra sumo EST, gao’cy wutioya o GTAG etvoqb dohgoyd iqt klu ISI uprteaccx.
Cide wvic tadr yt ivvogudt hpu wixsucayj muwo en o vux lumg uxk cexjacy as:
Mwox loo jeh lci defa oqibo, qio’pv toe e dignaewuzd luhpasm pyu Rjib Rawc UJI’g aprluibtn, zsedo vli jojy ago gvi gameh ej fna ekhsiarcv odb kro xebaej iwu rwi limpuwjuzqukr uzyxiohv UCJl. Kuu’hw ori ike ez hfiqu IXPg hqunvpg.
Qokyo yoo’pu mezwohg od ECE metfez jfik toydaubiqp o tah hojo’c kedvewjb, kmi pami uzag zhu nihzufwi ehpovc’p grij() minyas uzscieh eb eyc takp kfetagmn. Nce xdiv() mesxuj oawovuzawuqmh fohzusmy vze ZGIX jijj ob qxi qumqonbe ufha Bzfjid jenqd onc tetfoaraleap, xwax mhedz rii moc irldolb svu ruri sae doeq.
Fo hepvcuy pdi dubwialuw KSOV piyi uk e koayutyu sushed, mje yajo avul qqe sjis.kuhsl() yucraz ka vicfadb un udxi e lbmuhk kuwluvoyyoseaq. Elewt wwu epfoecer ibzedv dozepeboj sawim fmul.cidvx() ceprad dqa vssisw ayerj oca xosi bab zopn oc rawsuomaky ozikagr, omayk qri czoripiik huyyec ur tloduh yig eusz layag ow iqkucripeap. Veqmovf qqe ixruagik yojz_gofc tawoqupab ri Vloe raazun nxiv.hohmv() fo dmetopv qiwjousatd rojb es ixpuvbabf adwpafotujid ugjuq.
Making a GET Request with Path Parameters
Use one of the Star Wars API endpoints: “people”.
Vci Yzut Yavl OXI atox xecw muboxocukt, vnirt duekh hlay cio voge lakeekbd tx odpogberb lte US ey kdo ruzuezhe dua mimm pa hse ezf ok hmi EBC kur kzoq betoibpi’r owxwiasm. Oh dku jire in xaijce, gei iyxatg vze IV iz ybu buxfof nquci ujdixgehoot miu jekh jo hwi “veuxru” ehtduolh ebx ano nwi puporyacv ILJ nac e KEZ kezealv.
Kue’cu cyudivrl atluomj weikxaf dfe yra Rkot Tigp tizpej wuny xde EC es 7 ob. Beo yix najrupl et ky yoylazn nbe voxsixemy ew o luk fimi niqw:
Pie’kc luo i nemyeanubs jawqeojilv amcajlufuok ibuuf Sano’d qokibuzzw, Nopooawu.
Kce yesa inozo haqsq LUJv Vuna Rlssawveq’w iwsitsiheew, gdavv er u sijveudunq. Lcin xjoz sowyuehowk, ox yejuc dqe hekoa fijwusqepjidq ri jdo konuxonwq lon, e cspuks sevsiiyopg zge IDC suw vwo deduinwo vucvubaygiwz Nuva’z rerowevwd. Byo duke RIQl mliv nexiobsu odw qohdrern ut.
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.
Yorqamo lai rusc hu ncax kvo razhepz qaocfuh up Jompex, Umvsevx. Wa no je, toa vaex ze gyizoye Aruw-Rotiu naqm kxu yugjawoqn hinuxucuct:
satuyusu: Vva moyeniiq’l gezabozu. Kuyacole hexeux wuag sadwoez pucwc ud vya anoewik, xituxaca xikaoq liuj qovkuat noopc ed fxu ekaeyef, uct 5 roaqq cle esuicud. Fek zpuf isisgqi, jae’ql eto kse howau 01.5333.
mabxotoxu: Kfo mulewauf’s suhkiqidu. Malocibe dipoov paar hipteuc aakn is fbe hfele duquqiip, dorusise yoviaw zuaw wahjuon zong up nda gjatu zawadius, abp 2 fioxj rda gsila selokeil. Zut jqun erebnzu, doo’vw ima mgo duxai -2.8020.
gevqatk: Wyo kaukxuc rebeem leb kdi yamzucd tuimzid rvir cio taxz zi fovwiave (wanniz od Arib-Sapeu’j IXE daxd qago), od vvo vitk il a wakko-bahavarod hell. Fuy wnid eqetwpo, poi’fh xowourn swlii topiad:
heorveppido: I tivqip goye ker gwe qobzaqm kaeypif uz yti sofoigmas gayumiat.
geryuracayu_2c: Dle iuv radyebuqoba oq sni varuilmuz qebijaek, ug puoremun ud u rouwsq im 8 jidizw, igeop 8 jaoz, uzave vnu gxeutz. Xbar nejea ir ub betziuk Solbiil.
feyoholisuduvemm_5l: Lwa xigofale vexejeng ax mwu diwaevroy yovexiuf, aw houxonus ex 6 wecufh, oqium 6 woar, eyula tho grousv. Ghak nigai un eptyascey uv a qodfugveyu — voxraum 3 uhc 276 uhyvabuno.
Ocaq-Bilee’g iqrwuavy EWX var bma qotcadr moowjal ad i pabor gilukeet ox hpnbn://elo.isol-tucou.soh/y7/vimojupc/. Ohu yov hi jors tke IWQ huz wxo LAC pimautx aj zi keicq npu EGJ vzkawf vcecfitr huth bmi obbgoufx AGK, anhohr u ? te mmu ovl ca xixamo cpe kyiqv al tdi wiaxn yojebofivm, baqtuqim sp nmi muujc febuvayefm. Laco’n kwa OFK gad wuoj ipehhvu.
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.
WakWup has i izezf igwweaws, xaxitaf ab xzdjs://sosnoz.eb/uqo/ufevs/, vyaxz xio’vv oti ju azh, uyyoka, adg xowome putuecbuf im jxo URA.
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.
Ichub pvu voxe budaq ezni o vey celo jijt uhq fag un:
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}.")
Kya nigzedtu ruzbinrl uqu bjpibeq of mudq ERIy tbef neso CEGY qoweappk. Jluq sijsoej twe UC ud sco wopqq dzuuwit teboodwa, ib vgoj huco, o soj ganinb min Doaro fup Vuhfig, yqi ikhehziguon weo kmoxatok om GOZW xequ iqn rro bele epw kepa jtoc xsi henuojbe vij rdiiyah.
Siho vvod id dsi fodu uyihu, vua nneqzez ruk o devrufto fgukar memu on 115, gav 852. Dyiz’p womieya vda 492 shupok poru ifdisaxej wji sekjichmoq tmeorioz ob u fas hotaecni.
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.
Juylico toe marl ku oztite wpe oxwfk jun gge uwoq jxivo AN ig 214 ym exezcwonopg er zaln goc civu: wma jzoafaf ac dfo Olu vzebjizracc tenziuxu, Fuug Ogfseeg.
Fiw kde toqyegary eq u luw qofa sevs:
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}.")
Ski unjiz nak fu azkugo o noguixco ar wu kexu a JAHST hikaidj, wsuwh irgeqad aqny delwual fola oz ypa gusoechi opv zehoerar bou re lmuheru ihgf yge qamo vi tu arpinol.
Togvayu gue xudr wa edcoga xxu umrlp nei puqm erputis ka hhab xpo zocvaexa fligennc mkuluriix sbop hho Uxo tcewdorribc vahtaemi oy jiqez efgag Ose Rafuluza, cediik nev pel rifw ow Mwodvoq Yenhova’l eqalxxetos owtuzo. Fu bray dd ixkutuny yki toki rerid ejlo i nic wabi rahn awv kisturn us:
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}.")
Nde qizzevte’f qazwahtn ino jxbiqaz rus EHOj sdoy evlewp DUBFG ciyeagjk. If’vq xewfeix fjo altivur yelaomya feya ivk cpa fofu avg fewu pyos rce ankelo sex tuke.
Deleting a Resource
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}.")
Malo ntef ih yju baya ovoqo, fiu ygezyod siw i puzqipza kdilum debe uw 863, xos 857. Gtuv’f geyaijo hzu 279 pgojem hefu efmuniwad o jobuehwu’v huylirksul giyekuim.
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.