Advanced Chapter 164 · 30 min read · Module 12: Python Database and APIs
GET and POST Requests
- After this chapter you can explain when to use GET and when to use POST.
- You can send query parameters with GET using the params argument.
- You can send form data with data= and JSON with json= in a POST request.
- You can read the status code and JSON body that a POST returns.
- You can check the request that was sent by preparing it first.
Almost every web API call uses one of two methods. GET asks the server to give you something, and POST asks the server to accept something that you send. Reading a list of products is a GET. Creating a new order is a POST. Understanding the difference helps you write correct and safe API code.
Both methods are easy in the requests library: requests.get(url) and requests.post(url, ...). The part that needs care is how you send your data. GET puts it in the URL as query parameters, while POST puts it in the body of the request, either as form fields or as JSON.
In this chapter you will compare the two methods and send data in each way. To make every example safe and repeatable, the runnable code starts a tiny server on your own computer. The server stores the items you post and returns them with a GET, so you can see the whole cycle.
GET: asking for data
A GET request has no body. Any options go into the URL after a question mark. GET is meant for reading, so it should never change data on the server. Because the data is in the URL, a GET can be saved as a bookmark and can be cached. It also means that you must never place passwords or private tokens in the query string, because URLs are often stored in logs.
POST: sending data
A POST request carries a body. The server reads the body and usually creates something new. If the creation works, the usual answer is status 201 Created with details of the new item. POST is not idempotent, so sending the same request twice may create two items. Be careful with retries.
| Point | GET | POST |
|---|---|---|
| Purpose | Read data | Send or create data |
| Data location | URL query string | Request body |
| Body allowed | No | Yes |
| Can change server data | No (should not) | Yes |
| Size limit | Short, limited by URL length | Much larger |
| Repeating it | Same result | May create duplicates |
Form data and JSON bodies
There are two common body formats. With data={...} requests sends form encoded text such as name=Asha&age=21, the same format that an HTML form uses. With json={...} requests converts the dictionary to JSON and also sets the header Content-Type: application/json. Most modern APIs expect JSON.
You can look at what requests will send, before sending anything, by preparing the request. The prepared request has a body and headers that you can print.
import requests
form = requests.Request("POST", "https://api.example.com/users", data={"name": "Asha", "age": 21}).prepare()
print(form.body)
print(form.headers["Content-Type"])
as_json = requests.Request("POST", "https://api.example.com/users", json={"name": "Asha", "age": 21}).prepare()
print(as_json.body)
print(as_json.headers["Content-Type"])A full cycle on your own computer
The example below starts a local server. It then sends a POST with form data, a POST with JSON, and finally a GET that lists everything that was stored. The server code is only there to make the demo work. Focus on the client lines that use the session object, which behaves like the plain requests functions.
import requests
import threading, json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
ITEMS = []
class Handler(BaseHTTPRequestHandler):
def reply(self, status, data):
body = json.dumps(data, sort_keys=True).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
parts = urlparse(self.path)
if parts.path == "/items":
self.reply(200, ITEMS)
else:
self.reply(404, {"error": "not found"})
def do_POST(self):
size = int(self.headers.get("Content-Length", 0))
raw = self.rfile.read(size).decode()
kind = self.headers.get("Content-Type", "")
if kind == "application/json":
data = json.loads(raw)
else:
data = {k: v[0] for k, v in parse_qs(raw).items()}
ITEMS.append(data)
self.reply(201, {"saved": data, "count": len(ITEMS)})
def log_message(self, *args):
pass
def start():
server = HTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
server = start()
base = f"http://127.0.0.1:{server.server_port}"
session = requests.Session()
session.trust_env = False
r1 = session.post(base + "/items", data={"name": "pen", "qty": "3"})
print(r1.status_code, r1.json())
r2 = session.post(base + "/items", json={"name": "book", "qty": 1})
print(r2.status_code, r2.json()["count"])
r3 = session.get(base + "/items")
print(r3.status_code)
for item in r3.json():
print(item["name"], item["qty"])
print(session.get(base + "/nothing").status_code)
server.shutdown()Look at the types. The form post stored the quantity as the text "3", because form data has only text. The JSON post kept the quantity as the number 1. This is one good reason to prefer JSON when your data has numbers, lists or nested objects.
Checking the result
After each call, look at the status code first. For a POST that creates something, expect 201, though some APIs return 200. A 400 means the data you sent was not accepted, 401 means you are not logged in, and 422 often means the data was well formed but failed validation. Then read the body with response.json(). Wrap the call in try and except, and always pass a timeout.
import requests
payload = {"title": "Learn APIs", "done": False}
try:
r = requests.post("https://api.example.com/todos", json=payload, timeout=5)
r.raise_for_status()
print(r.status_code)
print(r.json())
except requests.exceptions.RequestException as err:
print("Problem:", err)Other methods in one glance
The same style works for the other methods: requests.put, requests.patch and requests.delete. PUT replaces an item, PATCH changes part of it, and DELETE removes it. Once you know GET and POST, these are only small changes.
params= for GET options, and json= or data= for POST bodies. Mixing them up is the most common beginner mistake.Python syntax
requests.get(url, params={"key": "value"}, timeout=5)requests.post(url, json={"key": "value"}, timeout=5)requests.post(url, data={"field": "value"}, timeout=5)Real-world applications
- Searching a catalogue with filters using GET.
- Submitting a sign up form with POST.
- Creating a task, a post or an order through an API.
- Sending a chat message to a bot service.
- Logging in to get a token.
Common mistakes
Fix: Put tokens in headers and private data in a POST body over HTTPS.
Fix: Use json= so that the body and the Content-Type header are correct.
Fix: Use POST, PUT, PATCH or DELETE for changes.
Fix: Check whether the item was created before you retry, or use an idempotency key if the API supports it.
Fix: data= makes form text. Use json= for JSON.
Important tips
- Read the API docs to see whether it expects form data or JSON.
- Print the status code and body of every early test.
- Use prepared requests to inspect what you will send.
- Always send HTTPS requests for private data.
Key points summary
- GET reads, POST sends.
- GET data lives in the URL, POST data lives in the body.
- data= sends form text and json= sends JSON.
- A successful create returns 201.
- POST is not idempotent, so retries need care.
Exam and interview points
- GET: read, data in URL. POST: create, data in body.
- json= sets Content-Type to application/json.
- data= sends application/x-www-form-urlencoded.
- 201 Created is the usual POST success code.
- POST is not idempotent.
Quick revision
- requests.get(url, params=...)
- requests.post(url, json=...)
- Form data is text only.
- Check status_code, then json().
- Never put secrets in a GET URL.
Frequently asked questions
Can a GET request have a body?
Technically it can, but servers ignore it or reject it. Use POST when you need to send a body.
Is POST more secure than GET?
It hides data from the URL and logs, but it is not encrypted by itself. Only HTTPS protects the data.
How do I send both a token and JSON?
Pass json= for the body and headers={'Authorization': 'Bearer ...'} for the token.
What if I get status 415?
The server does not support the content type that you sent. Check whether it expects JSON or form data.
Practise this chapter
19 practice questions Take the chapter quiz