Python Making HTTP Requests
Table of Contents + −
In the last lesson you learned What is an API?. You saw that an API is a way for one program to ask another program for data. Now here is the next question. How does that asking actually happen over the internet? The answer is HTTP. It is the language the web uses to talk. Let me show you how it works.
🤔 Why HTTP Matters
Say you want your Python program to grab the latest weather. Or post a message to a chat app. Or read a list of products from an online store. All of that data lives on some other computer far away. Your program can’t just reach over and take it. It has to ask. And it has to ask in a way the other computer understands.
That shared way of asking is HTTP. HTTP stands for HyperText Transfer Protocol. A protocol is just an agreed set of rules for how two computers talk to each other. Every time you open a website, your browser is speaking HTTP without you noticing. When your Python program talks to an API, it speaks the same language.
So here is the problem. Your data is on another machine. You need a polite, agreed way to ask for it. HTTP is that agreed way.
🌐 The Request and Response Idea
HTTP works like a short conversation with two turns. You send a request. The server sends back a response. That’s it.
Think of it like ordering food at a counter. You walk up and say what you want. That is the request. The person hands you your order, or tells you they are out of it. That is the response. Your program is the customer. The server is the person behind the counter.
Here is what each side carries:
- The request says what you want and where you want it from. It also says whether you are reading data or sending data.
- The response carries the data you asked for. It also carries a small number that tells you whether things went well.
Every API call you ever make follows this same back-and-forth shape. Once you see it, you will spot it everywhere.
📨 HTTP Methods: GET and POST
When you send a request, you have to say what kind of action you want. This is called the HTTP method. There are several. Two of them cover most of what you will do at the start.
Here is the plain-English version of each:
- GET means “give me data.” You use GET to read things. Reading a list of users, fetching today’s weather, loading a product page. GET takes data out. It doesn’t change anything on the server.
- POST means “here is some new data, please save it.” You use POST to send things. Signing up a new user, posting a comment, uploading a photo. POST hands data to the server so it can store it or act on it.
A quick way to remember it is this. GET reads, POST sends.
There are a few more methods you will meet later. Here is the short list so the names are not a surprise:
| Method | What it does | Everyday example |
|---|---|---|
| GET | Read data | Loading your YouTube feed |
| POST | Send new data | Posting a new comment |
| PUT | Update existing data | Editing your profile name |
| DELETE | Remove data | Deleting a photo |
For now, just keep GET and POST in your head. Those two will carry you a long way.
🔗 URLs and Endpoints
Every request needs an address. Without one, the server would not know where to send your question. That address is the URL.
A URL is the web address you type into a browser, like https://api.github.com/users/alex. When a URL points at a specific spot in an API that gives you specific data, we call it an endpoint. So an endpoint is just a URL with a job.
Let me break a URL into its parts so it stops looking like a wall of text:
| Part | Example | What it means |
|---|---|---|
| Scheme | https | How to connect. https is the secure version. |
| Host | api.github.com | Which server to talk to. |
| Path | /users/alex | The exact thing you want from that server. |
So when your program sends a GET request to https://api.github.com/users/alex, you are saying “connect securely to GitHub’s API server and give me the user data for alex.” The whole address together is the endpoint.
🔢 Status Codes
When the server replies, it includes a small number called a status code. This number tells you, at a glance, how the request went. You don’t have to read the whole response to know if it worked. You just look at the number.
A status code is a three-digit number the server sends back. It says one of a few things. “All good.” “That doesn’t exist.” Or “something broke.” They come in groups based on the first digit.
Here are the ones you will see most:
| Code | Name | What it means |
|---|---|---|
| 200 | OK | It worked. Your data is in the response. |
| 201 | Created | Your POST worked and new data was saved. |
| 404 | Not Found | The thing you asked for isn’t there. |
| 500 | Server Error | Something broke on the server’s side, not yours. |
Here is an easy way to remember the groups. 2xx means success. 4xx means you made a mistake, like asking for a page that doesn’t exist. And 5xx means the server made the mistake. The famous 404 you have seen on broken web pages? That is the same 404 your program gets back from an API.
Tip
When something goes wrong with an API call, the status code is the first thing to check. A 404 means fix your URL. A 500 means wait and try again, because the problem is on the server, not in your code.
🐍 A First Look at requests
Python can speak HTTP, but the built-in tools for it are a bit clumsy. So almost everyone uses a friendly third-party library called requests. It turns a whole HTTP request into one simple line.
Since requests is not built into Python, you install it first. It is a third-party library, so you bring it in with pip:
pip install requestsNow here is the simplest possible GET request. We ask a public test API for a sample post and look at what comes back:
import requests
# Send a GET request to read data from an endpointresponse = requests.get("https://jsonplaceholder.typicode.com/posts/1")
# The status code tells us if it workedprint(response.status_code)
# .json() turns the response data into a Python dictionaryprint(response.json())Let’s walk through it line by line:
import requestsbrings in the library so we can use it.requests.get(...)sends a GET request to that URL and waits for the reply. The whole response comes back and we store it inresponse.response.status_codeis the status number we just learned about. We print it to check things went well.response.json()reads the data the server sent and turns it into a Python dictionary, so you can work with it like normal Python.
This call goes out to a real server on the internet. So the exact output depends on that server. Here is realistic example output of what you would see:
Output
200{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}The 200 tells you the request worked. The dictionary after it is the actual data the server sent back. From here you could pull out response.json()["title"] and use it however you like, just like any other Python dictionary.
Note
This is only a first taste of requests. We kept it to a single GET so the HTTP idea stays front and center. The next lesson goes deep on requests, including how to send data with POST and how to handle errors cleanly.
⚠️ Common Mistakes
A few things trip people up early. Watch for these.
- Using GET when you mean to send data. GET is for reading. If you are saving or creating something, reach for POST.
# ❌ Avoid: using GET to create a new user (GET is for reading)response = requests.get("https://api.example.com/users")
# ✅ Good: use POST to send new dataresponse = requests.post("https://api.example.com/users", json={"name": "Riya"})- Assuming the request always worked. A reply with status 404 or 500 is still a reply. Your code keeps running. Always check the status code before you trust the data.
# ❌ Avoid: using the data without checking if the call succeededdata = requests.get(url).json()
# ✅ Good: check the status code firstresponse = requests.get(url)if response.status_code == 200: data = response.json()- Forgetting https. Most APIs need the secure
https://address, nothttp://. Leave it off or use the wrong one and the request fails before it starts. - Misreading a 500 as your bug. A 500 means the server broke, not your code. Don’t spend an hour rewriting a request that was fine.
✅ Best Practices
These habits keep your API code reliable:
- Always check
response.status_codebefore you use the data. - Use GET to read and POST to send. Match the method to the action.
- Store the base URL in a variable instead of typing the full address everywhere.
- Read the API’s documentation to find the right endpoint and method. Every API publishes one.
- Treat the status code as your first clue when something goes wrong.
🧩 What You’ve Learned
Here is the quick recap of what you can now explain:
- ✅ HTTP is the agreed language computers use to talk over the web, built on a request and a response.
- ✅ GET reads data and POST sends data, and there are a few more methods like PUT and DELETE.
- ✅ A URL is a web address, and an endpoint is a URL that points at specific data in an API.
- ✅ Status codes tell you how a request went: 200 means OK, 404 means not found, and 500 means a server error.
- ✅ The requests library lets you make an HTTP request in one clean line of Python.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Which HTTP method would you use to read a list of products from an API?
Why: GET is the method for reading data; it takes data out without changing anything on the server.
- 2
What does a 404 status code mean?
Why: 404 Not Found means the resource you requested does not exist, usually because of a wrong URL.
- 3
In the URL https://api.github.com/users/alex, what is /users/alex?
Why: The path tells the server exactly which thing you want from it; combined with the host it forms the endpoint.
- 4
A status code in the 5xx group, like 500, tells you what?
Why: 5xx codes mean the error is on the server's side, not in your request, so trying again later often helps.
🚀 What’s Next?
You now know the shape of every web request: a method, a URL, and a status code that comes back. Next we will spend real time with the tool that makes all of this easy in Python, including how to send data and handle errors properly.