# 422 Unprocessable Entity: Find the Field That Failed
> Source: https://scrape.do/blog/422-unprocessable-entity/
Published: 2026-11-30 · Updated: 2026-11-30 · Authors: Mert Bekci · Categories: Scraping Errors
Your request came back **422 Unprocessable Entity**: the server read it, understood its format, and rejected something inside it. Usually that's a missing field, a value of the wrong type or format, or a field the API doesn't take. The response body names the field, so read it before you touch the code. Python's `raise_for_status()` shows it as "422 Client Error: Unprocessable Entity for url" (newer servers say "Unprocessable Content").
The most common cause in Python is one keyword. `data=` sends your dict as a form, and a JSON API can't read fields out of it:
```python
import requests
URL = "https://gradio-hello-world.hf.space/gradio_api/call/predict"
payload = {"data": ["World"]}
bad = requests.post(URL, data=payload, timeout=30) # data= sends a form
error = bad.json()["detail"][0]
print(bad.status_code, bad.request.headers["Content-Type"])
print(error["msg"], "| the server got:", repr(error["input"]))
good = requests.post(URL, json=payload, timeout=30) # json= sends JSON
print(good.status_code, good.request.headers["Content-Type"], good.json())
```
```plaintext
422 application/x-www-form-urlencoded
Input should be a valid dictionary or object to extract fields from | the server got: 'data=World'
200 application/json {'event_id': 'bba48e8656244b0186147b8b676fef20'}
```
`json=` serializes the dict and sets `Content-Type: application/json` for you. With `data=`, the server got the string `'data=World'` and said so in the error. Sending the request again unchanged gets the same 422 every time; only a changed request gets a different answer.
> **Seeing it in Make, Zapier or Postman?** The API you called rejected a value in the data you mapped. Open the error's response body, find the field it names, and check that field's type and format against the API's docs.
## Find the Field the Error Names
GitHub's search API shows the simplest case. It's a GET with no body at all, and it still answers 422 when the query parameter is missing:
```bash
curl -s -w "\nHTTP %{http_code}\n" https://api.github.com/search/repositories
```
```json
{
"message": "Validation Failed",
"errors": [
{
"resource": "Search",
"field": "q",
"code": "missing"
}
],
"documentation_url": "https://docs.github.com/v3/search",
"status": "422"
}
HTTP 422
```
Most APIs answer in one of three shapes, and each puts the field somewhere else:
| Framework | Shape of the body | Where the field is |
|---|---|---|
| FastAPI (Pydantic) | `{"detail": [...]}` | `loc`, a path such as `["body", "items", 0, "qty"]` |
| Rails, Laravel | `{"errors": {"field": ["message"]}}` | The keys of `errors` |
| GitHub | `{"message", "errors": [...]}` | `field` in each entry |
[Laravel's validation docs](https://laravel.com/docs/validation) describe its version: a JSON request that fails validation gets a 422 with a `message` and an `errors` object. This helper reads all three shapes:
```python
import requests
def explain_422(r):
"""Print the field errors from the common 422 body shapes."""
body = r.json()
if isinstance(body.get("detail"), list): # FastAPI and Pydantic
for e in body["detail"]:
where = ".".join(str(part) for part in e["loc"])
print(f" {where}: {e['msg']} (type={e['type']}, input={e.get('input')!r})")
elif isinstance(body.get("errors"), dict): # Rails and Laravel
for field, messages in body["errors"].items():
print(f" {field}: {'; '.join(messages)}")
elif isinstance(body.get("errors"), list): # GitHub
for e in body["errors"]:
print(f" {e.get('field')}: {e.get('code')} ({body.get('message')})")
else:
print(" ", body)
r = requests.get("https://api.github.com/search/repositories", timeout=30)
print(r.status_code, r.reason)
explain_422(r)
r = requests.post("https://gradio-hello-world.hf.space/gradio_api/call/predict", json={}, timeout=30)
print(r.status_code, r.reason)
explain_422(r)
```
```plaintext
422 Unprocessable Entity
q: missing (Validation Failed)
422 Unprocessable Content
body.data: Field required (type=missing, input={})
```
The second URL is Gradio's official "hello world" demo on Hugging Face Spaces. Gradio serves its API with FastAPI, so these are real FastAPI validation errors. `body.data` is the field `data` in the request body, and `input={}` is what the server actually got.
The first part of `loc` is where FastAPI looked for the value: `body`, `query`, `path` or `header`. A `query` error on a request you sent as JSON means the endpoint reads that parameter from the query string, which is the case behind [a much-upvoted Stack Overflow question](https://stackoverflow.com/questions/59929028/python-fastapi-error-422-with-post-request-when-sending-json-data) on FastAPI 422s.

Once you know the field, the cause is usually one of these. The first five are about the values; the last three are about how the request was sent:
| Cause | Example | Where we reproduced it |
|---|---|---|
| A required field is missing | No `q` on a search, no `data` on a call | GitHub API, FastAPI app |
| A value has the wrong type | A string where the API wants a list or an integer | FastAPI app, local server |
| A value has the wrong format | `30/11/2026` where the API wants `2026-11-30` | Local server |
| A field the API doesn't accept | `coupon` on an endpoint that forbids extra fields | Local server |
| A nested object is wrong | `items[0].qty` is 0, `items[1].sku` is missing | Local server |
| JSON sent as form data | `requests` with `data=`, curl with `-d`, `fetch` with an object | FastAPI app |
| Broken JSON | A trailing comma or an unclosed list | FastAPI app, local server |
| A missing or stale CSRF token | A form POST copied from DevTools | Local server (Rails behavior) |
If you send requests through [Scrape.do's web scraping API](/products/web-scraping-api/), the target's 422 body comes back to you unchanged, and the `Scrape.do-Initial-Status-Code` header shows the status the target sent. Add `transparentResponse=true` when you need the target's exact status code on every response. You can [get a free API token](https://dashboard.scrape.do/signup) and point it at the endpoint that's failing.
## When Your JSON Never Arrived as JSON
"My JSON looks right" usually means the JSON never reached the server as JSON. `data=` in requests is one way. Node's `fetch` and curl have their own, and each leaves a recognizable trace in the error.
### fetch Sends "[object Object]"
Pass a plain object as `body` and `fetch` turns it into the string `[object Object]`, sent as text:
```javascript
const url = "https://gradio-hello-world.hf.space/gradio_api/call/predict";
const payload = { data: ["World"] };
// Wrong: fetch turns a plain object into the string "[object Object]"
const bad = await fetch(url, { method: "POST", body: payload });
console.log(bad.status, (await bad.json()).detail[0]);
// Right: serialize the body and say it's JSON
const good = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
console.log(good.status, await good.json());
```
Save it as `fetch_422.mjs` and run it with `node fetch_422.mjs` (Node 18 or later has `fetch` built in):
```plaintext
422 {
type: 'model_attributes_type',
loc: [ 'body' ],
msg: 'Input should be a valid dictionary or object to extract fields from',
input: '[object Object]'
}
200 { event_id: 'ee980b3c4d7c4b6b80a50e82eb33576b' }
```
`input: '[object Object]'` gives it away, so search your logs for that string when a Node client gets a 422 it can't explain. With `fetch`, serializing the body is your job: `JSON.stringify` plus the `Content-Type` header.
### curl -d Labels JSON as a Form
`-d` on its own sends `Content-Type: application/x-www-form-urlencoded`, even when the text is JSON:
```bash
URL=https://gradio-hello-world.hf.space/gradio_api/call/predict
# -d alone sends Content-Type: application/x-www-form-urlencoded
curl -s -w " HTTP %{http_code}\n" -X POST "$URL" -d '{"data": ["World"]}'
# --json sets Content-Type and Accept to application/json
curl -s -w " HTTP %{http_code}\n" "$URL" --json '{"data": ["World"]}'
```
```plaintext
{"detail":[{"type":"model_attributes_type","loc":["body"],"msg":"Input should be a valid dictionary or object to extract fields from","input":"{\"data\": [\"World\"]}"}]} HTTP 422
{"event_id":"1c747143b55e472eab70b7b73acae79c"} HTTP 200
```
The JSON text arrived intact but labelled as a form, so the server treated it as one long string. `--json` (curl 7.82 and later) fixes it, and so does adding `-H "Content-Type: application/json"` to the `-d` command.
### A Trailing Comma
Broken JSON is one more way. Many APIs answer it with a 400, but FastAPI calls it a 422 too:
```bash
curl -s https://gradio-hello-world.hf.space/gradio_api/call/predict -H "Content-Type: application/json" -d '{"data": ["World"],}'
```
```json
{"detail":[{"type":"json_invalid","loc":["body",18],"msg":"JSON decode error","input":{},"ctx":{"error":"Illegal trailing comma before end of object"}}]}
```
`json_invalid` with a number in `loc` gives the character position where parsing failed.
## Valid JSON, Wrong Values
Once the body arrives as JSON, the remaining 422s are about values. The Gradio demo requires `data` to be a list and `session_hash` to be a string:
```python
import requests
URL = "https://gradio-hello-world.hf.space/gradio_api/call/predict"
for payload in ({"data": "World"}, {"data": ["World"], "session_hash": 123}, {"data": ["World"]}):
r = requests.post(URL, json=payload, timeout=30)
detail = r.json().get("detail", [{}])[0] if r.status_code == 422 else r.json()
print(r.status_code, payload, "->", detail.get("msg", detail))
```
```plaintext
422 {'data': 'World'} -> Input should be a valid list
422 {'data': ['World'], 'session_hash': 123} -> Input should be a valid string
200 {'data': ['World']} -> {'event_id': '55787bffda1e4f2a87c3f88e10d92587'}
```
Each error names the type the API expected. If you build the payload from scraped or user input, convert the types before you send: `int()` for IDs, a list around a single value, `str()` for tokens.
## 422 vs 400 (and 415): What the Specs Say, What APIs Do
[RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#status.422), the current HTTP semantics standard, defines 422 in section 15.5.21. The server "understands the content type of the request content (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but it was unable to process the contained instructions."
The code started in WebDAV. [RFC 4918](https://www.rfc-editor.org/rfc/rfc4918#section-11.2) defined it as 422 Unprocessable Entity, and RFC 9110 moved it into core HTTP "because of its general applicability" and renamed it **422 Unprocessable Content**. Both names mean the same status, and you'll see both in the wild:
| Server | Status line it sends |
|---|---|
| GitHub's REST API | `HTTP/1.1 422 Unprocessable Entity` |
| A FastAPI app, and recent Python versions' own `http.server` | `HTTP/1.1 422 Unprocessable Content` |
On paper the split is clean: 400 when the server can't parse the request, 415 when it won't read the body's media type, 422 when it parsed the body and rejected the content. GitHub's Markdown API follows it, with a 400 and a 422 on one endpoint:
```python
import requests
URL = "https://api.github.com/markdown"
tests = [
("form body", {"data": {"text": "**hi**"}}),
("JSON, no text", {"json": {"mode": "gfm"}}),
("JSON, text is a number", {"json": {"text": 123}}),
("JSON, valid", {"json": {"text": "**hi**"}}),
]
for label, kwargs in tests:
r = requests.post(URL, timeout=30, **kwargs)
answer = r.json()["message"] if r.status_code >= 400 else r.text.strip()
print(f"{label:24} {r.status_code} {answer}")
```
```plaintext
form body 400 Problems parsing JSON
JSON, no text 422 Missing or invalid 'text' attribute in JSON request
JSON, text is a number 422 Missing or invalid 'text' attribute in JSON request
JSON, valid 200
hi
```
GitHub couldn't parse the form body, so it said 400. It parsed both JSON bodies and found `text` missing or of the wrong type, so it said 422. FastAPI used 422 for the same form body, and Rails maps a failed CSRF check to 422 in its [default exception mapping](https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb). Where the line falls is each framework's choice, so read the body as well as the code before you pick a fix.
| Code | What it means | What to check | Does changing the request help? |
|---|---|---|---|
| 422 Unprocessable Entity | The body parsed, but its content failed validation | The fields the error body names | Yes, fix those values |
| 400 Bad Request | The request is malformed or couldn't be parsed | The JSON syntax, the URL, the headers | Yes, fix the syntax |
| 415 Unsupported Media Type | The server can't read the body's format | Your request's `Content-Type` | Yes, send a supported format |
| 406 Not Acceptable | No response format matches your `Accept` header | `Accept`, `Accept-Language` | Yes, usually one header |
| 403 Forbidden | The server understood and refuses you | Your IP, client and headers | Sometimes ([403 guide](/blog/python-requests-403-forbidden/)) |
| 429 Too Many Requests | Too many requests in a time window | `Retry-After` | No, slowing down does |
If you build an API, the original WebDAV definition is a good tiebreaker: a 422 request's syntax is correct, "thus a 400 (Bad Request) status code is inappropriate". Return field-level errors either way. Some errors never reach validation at all: through a proxy that fails before the target answers, you'll see a [407 Proxy Authentication Required](/blog/407-proxy-auth-required/), or ERR_TUNNEL_CONNECTION_FAILED in a browser, instead of a 422.
## Test Every Validation Rule on a Local Server
Date formats, extra fields and nested objects need an endpoint with those rules, so we wrote one that uses only Python's standard library. `/orders` returns FastAPI-style `detail` errors (the types and messages follow Pydantic's wording), `/users` returns a Rails-style `errors` object, and `/search` is a form protected by a CSRF token:
```python
import json
import re
import secrets
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
SESSIONS = {} # session cookie -> CSRF token, like a Rails session store
REJECTED = "The change you wanted was rejected.
"
def err(kind, loc, msg, value, **ctx):
e = {"type": kind, "loc": ["body", *loc], "msg": msg, "input": value}
return {**e, "ctx": ctx} if ctx else e
def validate_order(body):
"""FastAPI-style checks: required fields, types, a date, nested items, no extras."""
if not isinstance(body, dict):
return [err("model_attributes_type", [], "Input should be a valid dictionary "
"or object to extract fields from", body)]
errors = [err("missing", [f], "Field required", body)
for f in ("customer_id", "email", "ship_date", "items") if f not in body]
errors += [err("extra_forbidden", [f], "Extra inputs are not permitted", body[f])
for f in body if f not in ("customer_id", "email", "ship_date", "items")]
cid = body.get("customer_id", 0)
if not isinstance(cid, int) and not str(cid).isdigit():
errors.append(err("int_parsing", ["customer_id"], "Input should be a valid integer, "
"unable to parse string as an integer", cid))
day = str(body.get("ship_date", "2026-01-01"))
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
errors.append(err("date_from_datetime_parsing", ["ship_date"], "Input should be a "
"valid date or datetime, invalid character in year", day))
for i, item in enumerate(body.get("items", [])):
if "sku" not in item:
errors.append(err("missing", ["items", i, "sku"], "Field required", item))
if item.get("qty", 1) < 1:
errors.append(err("greater_than_equal", ["items", i, "qty"],
"Input should be greater than or equal to 1", item["qty"], ge=1))
return errors
class Handler(BaseHTTPRequestHandler):
def do_GET(self): # a Rails-style search form with a CSRF token in a hidden field
sid, token = secrets.token_hex(8), secrets.token_urlsafe(16)
SESSIONS[sid] = token
form = f''
self.reply(200, form, "text/html", {"Set-Cookie": f"_session_id={sid}"})
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode()
ctype = self.headers.get("Content-Type", "")
if self.path == "/orders":
if "json" in ctype or not ctype:
try:
body = json.loads(raw)
except json.JSONDecodeError as e:
errors = [err("json_invalid", [e.pos], "JSON decode error", {}, error=e.msg)]
return self.reply(422, json.dumps({"detail": errors}))
else:
body = raw # form data or text: FastAPI keeps the raw string
errors = validate_order(body)
if errors:
return self.reply(422, json.dumps({"detail": errors}))
return self.reply(201, json.dumps({"id": 1001, **body}))
if self.path == "/users": # Rails style: {"errors": {"field": ["message"]}}
user = json.loads(raw or "{}").get("user", {})
errors = {}
if not user.get("email"):
errors["email"] = ["can't be blank"]
if len(user.get("name", "")) < 2:
errors["name"] = ["is too short (minimum is 2 characters)"]
return self.reply(422 if errors else 201, json.dumps({"errors": errors} if errors else user))
if self.path == "/search": # the form posts back here; no valid token, no results
sid = re.search(r"_session_id=(\w+)", self.headers.get("Cookie", ""))
sent = parse_qs(raw).get("authenticity_token", [""])[0]
if not sid or SESSIONS.get(sid.group(1)) != sent:
return self.reply(422, REJECTED, "text/html")
return self.reply(200, json.dumps({"results": ["Acme Widget", "Acme Gadget"]}))
self.reply(404, '{"detail": "Not Found"}')
def reply(self, status, body, ctype="application/json", headers=None):
self.send_response(status)
self.send_header("Content-Type", ctype)
for name, value in (headers or {}).items():
self.send_header(name, value)
self.end_headers()
self.wfile.write(body.encode())
def log_message(self, *args): # keep the console quiet
pass
HTTPServer(("127.0.0.1", 8422), Handler).serve_forever()
```
Save it as `server_422.py` and start it in its own terminal:
```bash
python server_422.py
```
Now send it an order with five things wrong at once: an ID that isn't a number, a date in the wrong format, a quantity of zero, an item without a SKU, and a field the API doesn't accept:
```python
import requests
order = {
"customer_id": "C-42", # the API wants an integer
"email": "buyer@example.com",
"ship_date": "30/11/2026", # the API wants YYYY-MM-DD
"items": [{"sku": "A-1", "qty": 0}, {"qty": 2}],
"coupon": "WELCOME10", # a field the API doesn't accept
}
r = requests.post("http://127.0.0.1:8422/orders", json=order, timeout=10)
print(r.status_code, r.reason)
for e in r.json()["detail"]:
print(" ", ".".join(map(str, e["loc"])), "->", e["msg"], f"(got {e['input']!r})")
```
```plaintext
422 Unprocessable Content
body.coupon -> Extra inputs are not permitted (got 'WELCOME10')
body.customer_id -> Input should be a valid integer, unable to parse string as an integer (got 'C-42')
body.ship_date -> Input should be a valid date or datetime, invalid character in year (got '30/11/2026')
body.items.0.qty -> Input should be greater than or equal to 1 (got 0)
body.items.1.sku -> Field required (got {'qty': 2})
```
(Older Pythons send the reason phrase `Unprocessable Entity`; the number is what counts.)
FastAPI-style APIs report every problem in one response, so fix them all before you resend, or you'll pay one round trip per error. Paths like `body.items.0.qty` point into nested objects: here, the first item's `qty`.
The local server reproduces both "never arrived as JSON" cases too, a trailing comma and a form body:
```python
import requests
URL = "http://127.0.0.1:8422/orders"
text = '{"customer_id": 42, "email": "buyer@example.com",}' # trailing comma
r = requests.post(URL, data=text, headers={"Content-Type": "application/json"}, timeout=10)
print(r.status_code, r.json()["detail"][0])
r = requests.post(URL, data={"customer_id": 42}, timeout=10) # a form, not JSON
print(r.status_code, r.json()["detail"][0]["msg"])
```
```plaintext
422 {'type': 'json_invalid', 'loc': ['body', 48], 'msg': 'JSON decode error', 'input': {}, 'ctx': {'error': 'Illegal trailing comma before end of object'}}
422 Input should be a valid dictionary or object to extract fields from
```
The `ctx.error` text comes from the server's Python JSON parser, so older Python versions word it differently: they report "Expecting property name enclosed in double quotes" for the same trailing comma.
A Rails-style API puts the same information in an `errors` object keyed by field name:
```python
import requests
r = requests.post("http://127.0.0.1:8422/users", json={"user": {"name": "A"}}, timeout=10)
print(r.status_code, r.json())
for field, messages in r.json()["errors"].items():
for message in messages:
print(f"{field.capitalize()} {message}")
```
```plaintext
422 {'errors': {'email': ["can't be blank"], 'name': ['is too short (minimum is 2 characters)']}}
Email can't be blank
Name is too short (minimum is 2 characters)
```
Rails writes its messages to follow the field name, so joining them gives sentences you can log as they are.
## Catch Bad Payloads Before You Send Them
A check that runs in your own code costs nothing and reports every problem in your terms instead of the server's. You don't need a validation library for it; plain Python covers the rules behind most 422s:
```python
import re
import requests
REQUIRED = {"customer_id": int, "email": str, "ship_date": str, "items": list}
def check_order(order):
"""Return a list of problems; an empty list means the payload is safe to send."""
problems = [f"{k}: missing" for k in REQUIRED if k not in order]
problems += [f"{k}: not accepted" for k in order if k not in REQUIRED]
problems += [f"{k}: expected {t.__name__}, got {type(order[k]).__name__}"
for k, t in REQUIRED.items() if k in order and not isinstance(order[k], t)]
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(order.get("ship_date", ""))):
problems.append("ship_date: use YYYY-MM-DD")
for i, item in enumerate(order.get("items", [])):
if not isinstance(item.get("sku"), str):
problems.append(f"items[{i}].sku: missing")
if not isinstance(item.get("qty"), int) or item["qty"] < 1:
problems.append(f"items[{i}].qty: must be an integer of 1 or more")
return problems
order = {"customer_id": "C-42", "email": "buyer@example.com", "ship_date": "30/11/2026",
"items": [{"sku": "A-1", "qty": 0}], "coupon": "WELCOME10"}
print(check_order(order))
order = {"customer_id": 42, "email": "buyer@example.com", "ship_date": "2026-11-30",
"items": [{"sku": "A-1", "qty": 2}]}
problems = check_order(order)
if not problems:
r = requests.post("http://127.0.0.1:8422/orders", json=order, timeout=10)
print(r.status_code, r.json())
```
```plaintext
['coupon: not accepted', 'customer_id: expected int, got str', 'ship_date: use YYYY-MM-DD', 'items[0].qty: must be an integer of 1 or more']
201 {'id': 1001, 'customer_id': 42, 'email': 'buyer@example.com', 'ship_date': '2026-11-30', 'items': [{'sku': 'A-1', 'qty': 2}]}
```
If the API publishes an OpenAPI schema (FastAPI apps serve one at `/openapi.json` by default), take the required fields and types from it instead of guessing. If your project already uses Pydantic, a model with the same fields does this check for you.
## Replayed Requests and "The Change You Wanted Was Rejected"
A scraper that replays a site's hidden API gets a 422 when its payload differs from the one the page sends. Search and filter endpoints are where this happens most: you copy a POST from the DevTools Network tab, change the search term or the date range, and the API answers 422. Check these in order:
1. The body was re-encoded. "Copy as cURL" keeps the `Content-Type` header, but rewriting the call by hand often loses it. Send the same header as the browser, then use `json=`.
2. A value changed type or format. Pages often send numbers as numbers and dates in one exact format. `"page": "2"` instead of `"page": 2`, or `11/30/2026` instead of `2026-11-30`, is enough for a strict API.
3. A token is missing or stale. Many forms carry a CSRF token in a hidden field, tied to the session cookie. A token copied from DevTools belongs to your browser's session, not your script's.
4. The query is empty or too long. GitHub's search answers 422 when `q` is missing, and an empty search box in your loop does the same on many sites.
The CSRF case looks like this against the local server's `/search` form:
```python
import re
import requests
BASE = "http://127.0.0.1:8422"
# Replaying a form POST copied from DevTools: the token in it belongs to another session
copied = {"authenticity_token": "token-from-devtools", "q": "acme"}
r = requests.post(f"{BASE}/search", data=copied, timeout=10)
print(r.status_code, r.text)
# Load the form first in a session, then send the token it gave you
with requests.Session() as s:
page = s.get(f"{BASE}/search", timeout=10)
token = re.search(r'name="authenticity_token" value="([^"]+)"', page.text).group(1)
r = s.post(f"{BASE}/search", data={"authenticity_token": token, "q": "acme"}, timeout=10)
print(r.status_code, r.json())
```
```plaintext
422 The change you wanted was rejected.
200 {'results': ['Acme Widget', 'Acme Gadget']}
```
"The change you wanted was rejected." is the heading of the [default 422 page](https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/app/templates/public/422.html) Rails generates for new apps. Seeing it after a form POST almost always means a CSRF token problem. Fetch the page first, in the same session, and send the token it gives you.
To see what the browser sent, record the page as a [HAR file](/blog/har-file/) and open it in our [HAR analyzer](/tools/har-analyzer/). Then compare the request's `postData` and headers with your script's request, field by field.
### Sending POST Bodies Through Scrape.do
Scrape.do forwards the method, the body and its `Content-Type` to the target, as its [POST and PUT docs](/documentation/api-response/post-put-request/) show. Pass `json=` as you would for a direct call:
```python
import urllib.parse
import requests
token = ""
target = "https://gradio-hello-world.hf.space/gradio_api/call/predict"
api = f"https://api.scrape.do/?token={token}&url={urllib.parse.quote(target)}"
for payload in ({"data": ["World"]}, {}):
r = requests.post(api, json=payload, timeout=120)
print(r.status_code, r.headers.get("Scrape.do-Initial-Status-Code"), r.text)
```
```plaintext
200 200 {"event_id":"d0200a68c4d847668d29649062a018da"}
422 422 {"detail":[{"type":"missing","loc":["body","data"],"msg":"Field required","input":{}}]}
```
The valid body got a 200. The invalid one got the target's own 422 and error body, with `Scrape.do-Initial-Status-Code` confirming the target sent it, so you debug it the same way as a direct call. If the endpoint also needs your own headers, such as a token header from the HAR, send them with [`customHeaders=true`](/documentation/headers-cookies/custom-headers/) or add single headers with the `sd-` prefix of [extra headers](/documentation/headers-cookies/extra-headers/).
## Should I Retry a 422?
No. MDN's [422 page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/422) puts it plainly: a client "should expect that repeating the request without modification will fail with the same error." Keep 422 out of your retry list and fix the payload instead:
```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# 422 stays out of the list: the same request body fails the same way every time
retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
r = session.get("https://api.github.com/search/repositories", timeout=30)
print(r.status_code, "retries used:", len(r.raw.retries.history))
```
```plaintext
422 retries used: 0
```
The 422 came straight back, with no retries spent on it. Our guide to [retrying failed requests in Python](/blog/python-requests-retry/) covers the codes worth retrying, such as [429 Too Many Requests](/blog/429-too-many-requests/), and how to back off between attempts.
## Frequently Asked Questions
### What's the difference between Unprocessable Entity and Unprocessable Content?
They're the same status code. RFC 4918 (WebDAV) named 422 "Unprocessable Entity". RFC 9110 moved it into core HTTP and renamed it "Unprocessable Content". Servers send either phrase, and clients should only check the number.
### Why does FastAPI return 422 instead of 400?
FastAPI validates every request with Pydantic and reports any failure, including broken JSON and form data sent to a JSON endpoint, as a 422 with a `detail` list. Read `loc` in each entry to find the field. The app can change the status by overriding the `RequestValidationError` handler.
### How do I fix a 422 error in Postman?
In the Body tab, choose "raw" and "JSON" instead of "form-data" or "x-www-form-urlencoded", so Postman sends the JSON content type. Then read the response body: it names the field that failed, and the value you sent for it.