2. Making your first request

The best way to understand APIs is to see one in action. We'll start with something simple: calling an API directly in your browser, then repeating the same call in Python.

The Cat Facts API is a small, free service that returns random facts about cats. When you visit its URL in your browser, you're seeing exactly what the server sends back. No account, no API key, no setup. Perfect first stop.

Access the API in your browser

Before writing any Python, open this URL in your browser. That's you making an API request manually:

Browser
https://catfact.ninja/fact

You'll see a block of raw text in a format called JSON. It looks a little dense at first, but it's just structured text that your computer can read easily. Your browser sent a request to the server, and the server responded with this JSON. A Python program would receive exactly the same data. Under the hood, almost all API responses look like this: structured text that code can parse and work with.

Now try it in Python

Now we'll make that exact same request from Python. You're going to write four lines that connect to a live server, send a request, and print the data that comes back. Notice how little code is needed: the requests library hides all the low-level networking details for you.

Save this as first_request.py at the root of your project:

first_request.py
import requests

url = "https://catfact.ninja/fact"
response = requests.get(url)

print(response.text)

Run it from the project root:

Terminal
$ python first_request.py
{"fact":"Cats have five toes on their front paws, but only four on the back ones.","length":72}

In just a few lines of code, you connected to a live server on the internet and received real data back. This is exactly how your phone's apps talk to servers. The only difference is that you're now in control of the conversation.

What just happened

Line by line:

  • import requests loads the library that knows how to talk to web servers.
  • requests.get(url) sends a GET request to that URL, asking for data.
  • response.text is the raw text the server sent back.

Your computer packaged up an HTTP request, sent it across the internet to catfact.ninja's servers, waited for the response, and received structured data back, all in a fraction of a second.

The output looks like a Python dictionary, but right now it's just a string of text. The curly braces and colons are characters Python doesn't understand yet. In the next section, we'll turn that string into a real Python object you can actually work with.