DEV Community

Cover image for Beginner's Guide to Requests and APIs
Elijah Jeremiah L. Barba
Elijah Jeremiah L. Barba

Posted on

Beginner's Guide to Requests and APIs

The requests module is your portal to the open web.🤯 Basically any API that you have access to, you can pull data from it (Though your mileage may vary).

Getting Started ✊

Installing requests needs pipenv, so go ahead and install that first if you don't have it. If you do, simply run this command:

pipenv install requests

Let's go ahead and pick an API to use.🤔

Here is a great resource to public APIs:

GitHub logo public-apis / public-apis

A collective list of free APIs for use in software and web development.

Public APIs Build Status

A collective list of free APIs for use in software and web development.

A public API for this project can be found here!

For information on contributing to this project, please see the contributing guide.

Please note a passing build status indicates all listed APIs are available since the last update. A failing build status indicates that 1 or more services may be unavailable at the moment.



API Description Auth HTTPS CORS

Let's use the API for this quick example:

Diving In 🙌

Let's import the all mighty:

import requests

And get-ting the data is pretty straightforward:

kanye_url = requests.get('')

Print it in JSON format:

# gets a random quote
# {'quote': 'Tweeting is legal and also therapeutic'}

It is important to read the docs of each API because each API is unique 🧐

Let's say we want to get a Chuck Norris joke from this API:
From the docs it uses a different URL, so let's go ahead and code that:

chuck_url = requests.get('')

... will output something like this:

{'categories': [], 'created_at': '2016-05-01 10:51:41.584544', 'icon_url': '', 'id': 'DLqW_fuXQnO1LtveTTAWRg', 'updated_at': '2016-05-01 10:51:41.584544', 'url': '', 'value': 'Chuck Norris Lost his virginity before his Dad...'}

...not exactly pretty to look at, so let's pretty-print it:💅

# 👇 Add this import below at the beginning of your file    
# import json

print(json.dumps(chuck_url.json(), indent=2))

Now it looks like this:

  "categories": [
  "created_at": "2016-05-01 10:51:41.584544",
  "icon_url": "",
  "id": "izjeqnjzteeqms8l8xgdhw",
  "updated_at": "2016-05-01 10:51:41.584544",
  "url": "",
  "value": "Chuck Norris knows the last digit of pi."

Now that's much more readable! 💪💪💪


Discussion (1)

thamaragerigr profile image
Thamara Gerig

Awesome!!!! Thanks!!!