[Python Tips] Requests
development·@themarkymark·
0.000 HBD[Python Tips] Requests
 **Requests is a powerful and easy to use HTTP library for Python** Need to get HTML data? Need to interact with an API? **Requests** can do that. While Python has a built-in library **urllib3** for these situations, **requests** wraps this library with an easy to use interface. # Installation To install requests, you can use pip to install it. `pip install -U requests` **The -U is a good practice to force an upgrade if it is already installed.** I recommend using a virtual environment. You can learn more about them in my previous tutorial on [Virtual Environments](https://steemit.com/programming/@themarkymark/python-tips-virtual-environments). # Usage While requests has a lot of functionality, I am going to cover the basic usage and you can refer to the documentation for the more advanced usage. #### Basic Query ``` import requests req = requests.get('https://pokeapi.co/api/v2/pokemon/ditto/`) ``` #### Status Codes You can verify you have a proper response by checking the status code. `req.status_code` 200 means everything went well, you can look up other codes [here](https://www.restapitutorial.com/httpstatuscodes.html). You can also use this technique to verify a good status code. `if req.status_code == requests.codes.ok:` There is a cleaner way to send a request and check the status code: ``` import requests req = req = requests.get('https://pokeapi.co/api/v2/pokemon/ditto/`) try: req.raise_for_status() except requests.exceptions.HTTPError as e: print e ``` #### Data You can retrieve the response data using `req.text`, `req.json()` as bytes with `req.content`, or raw with `req.raw`. Most of the time you will be using `req.json()` and will be able to use the result as normal json data. Requests can be used to **POST**, pass parameters, work with custom headers, and work with form data. If you want to learn other uses of the requests library, check out their [documentation](https://2.python-requests.org/en/master/). Requests is a simple by powerful python module that will handle 98% of your HTTP needs. # My Python Tips Series * [f-strings in Python 3.6](https://steemit.com/programming/@themarkymark/python-tips-f-strings-in-python-3-6-and-why-you-should-be-using-them) * [Underscores in numeric literals](https://steemit.com/programming/@themarkymark/python-tips-underscores-in-numeric-literals) * [A better interactive shell](https://steemit.com/programming/@themarkymark/python-tips-a-better-interactive-shell) * [Secrets Module - New in 3.6](https://steemit.com/programming/@themarkymark/python-tips-secrets-module-new-in-3-6) * [PEP 8](https://steemit.com/programming/@themarkymark/python-tips-pep-8) * [Slices](https://steemit.com/programming/@themarkymark/python-tips-slices) * [Named Tuples](https://steemit.com/programming/@themarkymark/python-tips-named-tuples) * [Destructuring](https://steemit.com/programming/@themarkymark/python-tips-destructuring) * [Counter](https://steemit.com/programming/@themarkymark/python-tips-counter) * [Type Annotation](https://steemit.com/programming/@themarkymark/python-tips-type-annotation) * [Jupyter Notebooks](https://steemit.com/programming/@themarkymark/python-tips-jupyter-notebooks) * [Getting Help](https://busy.org/@themarkymark/python-tips-getting-help) * [Virtual Environments](https://steemit.com/programming/@themarkymark/python-tips-virtual-environments) * [Expiring Dict](https://steemit.com/programming/@themarkymark/python-tips-expiring-dict) * [DRY Programming](https://steemit.com/programming/@themarkymark/python-tips-dry-programming) * [Knowing what exists](https://steemit.com/programming/@themarkymark/python-tips-knowing-what-exists) * [Apscheduler](https://steemit.com/utopian-io/@themarkymark/python-tips-apscheduler) * [Caching data with CacheTools](https://steemit.com/development/@themarkymark/python-tips-caching-data-with-cachetools) * [Walrus Operator](https://steemit.com/development/@themarkymark/python-tips-the-new-walrus-operator)
👍 stmdev, coredump, stemd, tonimontana.neo, toni.pal, wirednkod, vintageprint, laissez-faire, khaleelkazi, cryptopassionleo, r-pal, zaku-pal, priyo022, techken, kostybrat, samuelhull, gerber, one.life, exyle, accelerator, cadawg, bozz, bestboom, triptolemus, bobby.madagascar, steem.leo, leo.voter, general.guy, ctime, fsm-liquid, maxuvd, blockbrothers, triplea.bot, maxuva, maxuvc, maxuve, bilpcoinpower, nicestbot, buildawhale, leo.syndication, shadowspub, cwow2, ilias.fragment, brianhphotos, mirkon86, enforcer48, astil.codex, ezzy, bear8photo, pro.msibi, cervisia, yabapmatt, giftgiver, alexis555, igster, minersean, elevator09, lass3, rocky1, mangos, happy-soul, netaterra, travoved, wajahatsardar, tobias-g, snackaholic, vittoriozuccala, armandosodano, hiddendragon, vibvir, cst90, kryptogermany, detro10, busy.pay, felixpower, joythewanderer, etherpunk, isnochys, tipsybosphorus, moon32walker, nateaguila, purefood, goldneon, jphamer1, dreamarif, sourovafrin, kanrat, tonimontana, leotrail, chireerocks.pal, edgarare1, joeparys, alex2016, uyobong, tr3nches, thekitchenfairy, axeminni, cryptogem, rogz06, mohsen63, davidesimoncini, definethedollar, pladozero, leslierevales, bilderkiste, spielekiste, imacryptorick, bigmoneyman, bynarikode, gingerbyna, donbeano, nicnas, gokulramdas, hairshares, investfourmore, gtmatze, nilfanif, kessielynbote, playfulfoodie, epixar, fivefiveeleven, lazzelazer, demartini, shahab3211, khayziljoy, donnjoez, germanaure, saqibnazir, clearbluecrypto, renulia, journeyfreedom, thecreativerebel, evegrace, bobbypraize, giftakpan, blerdrage, luup, cryptkeeper17, beekerst, anyx, kushed, complexring, steemychicken1, aizensou, stoner19, sock, josephcraig289, igl00, hagie, coinbar, bigdaddy, kingsmind, pboc, papadimos, romedog, spg, sammosk, dream-o, tushy, richman, razvanelulmarin, fabio, shawnamawna, caesarion, thebluepanda, thisisbenbrick, einsteinpotsdam, tejma, allesgruen, dannystravels, jerryblanceton, ssekulji, timbernana, sherlockcupid, dougkarr, dark.horse, toyman, i-gordan, buzzbeergeek, sunshinetraveler, biancajapan, horsepower, teneiced, sumayyahsaidso, teslaman, blondephysics, magictoni, knozaki2016, seanlloyd, steemernoob, jvhteach, rambo21, cardboard, cfminer, profitcheck, tipu.curator, edkarnie, rollsman, stemgeeks, stemcuration, inertia, mrfringe, primeradue, world-cup, chrono.leo, mstafford, tonystarkalive, abitcoinskeptic, scaredycatguide, angelicsaman, ernstboe, galtsund, havtorn, doitvoluntarily, ljungbuske, manylar, seabuckthorn, meesterboom, sazbird, b00m, wisbeech, geekgirl, tysonjames, martie7, alexzicky, stem.curate, slider2990, gordonramzy, jessica.steem, sonomori609, paolo.senegal, quantumdeveloper, maruskina, nalacanecorso, btc4breackfast, alby2, riccc96, pecoshop, hjmarseille, boomalex, dolcesalato1981, mvd, darth-azrael, darth-cryptic, retrodroid, networkallstar, corsica, arson-crew, remlaps-lite, dr-frankenstein, bluerobo, steemflagrewards, wwwfernand, eastcore1, ansu55, torsteoe, yggdrasil.laguna, qurator, qtip, mariajruizb, gregory-f, yadamaniart, scrooger, qustodian, qberry, anomalogy, minimining, deeanndmathews, oleg326756, garudi, torachibi, blewitt, thisisawesome, awesomecuration, shikika, theleapingkoala, ntowl, coquiunlimited, jayna, foxyspirit, melooo182, mytechtrail, stem.alfa, guiltyparties, organduo.pal, laputis.pal, kharma.scribbles, coininstant, firealien, kdtkaren, honusurf, malia.mancianti, robinmmthompson, firealiean, me-we, mauialohabella, themarkymark, upmyvote, barton26, zorg67, mys, whd, rafalski, broncnutz, storysharing, mattsanthonyit, gtw, witnessbot, steem.observer, frasier, buildaminnow, contco, remindme.bot, steemelements, kehrwoche, grand.strategy, onespringday, abh12345.stem, holovision, steemseph, atanas007, accountsale, steamsteem, tolaramazan, slowgrow, stimialiti, atempt, fersher, selfvotejustice, cinefilm,