Skip to content

Calling Web APIs with requests

Beginning of the lesson

Calling Web APIs with requests

Talk to any web service from Python: send a request, read the response.

Big Idea: A web API lets your program ask another server for data or actions over HTTP. Python's requests library turns that whole conversation into a few readable lines: you pick an HTTP verb, aim it at a URL, maybe attach parameters or a JSON body, and read back a response with a status code and data.
By the end you will be able to:
  • send GET and POST requests with requests,
  • attach query parameters the safe way with params=,
  • send and read JSON bodies,
  • read and act on status codes (2xx / 4xx / 5xx),
  • handle timeouts and network errors without crashing.

1. What is a web API?

An API (Application Programming Interface) is a contract: a server publishes a set of URLs (called endpoints) and promises that if you send the right request, it will send back a useful response. A web API speaks over HTTP, the same protocol your browser uses.

Analogy: think of a restaurant. You (the client) do not walk into the kitchen. You give a waiter a specific order (the request); the kitchen prepares it and the waiter brings back a plate (the response). The menu is the API documentation: it tells you exactly what you can ask for and how.

The requests library is the de-facto standard way to be that client in Python. It is not in the standard library, so you install it once:

pip install requests

Then in your program you import it and make a call:

import requests

response = requests.get("https://api.example.com/status")
print(response.status_code)

2. HTTP verbs: what do you want to do?

Every request carries a verb (also called a method) that states your intent. requests gives you a function per verb:

VerbFunctionMeaningTypical use
GETrequests.get()Read dataFetch a weather report, a user profile
POSTrequests.post()Create something newSubmit a form, add a new record
PUTrequests.put()Replace a resource fullyOverwrite an existing profile
PATCHrequests.patch()Update part of a resourceChange just the email field
DELETErequests.delete()Remove a resourceDelete a saved item

GET should never change anything on the server (it is "safe" and can be retried freely). The verb is a promise about intent, so pick the one that matches what you are really doing.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers