Fix ValidationError: value is not a valid integer in FastAPI
This error occurs when a FastAPI endpoint receives data that does not match the Pydantic model's type annotations. For example, passing a string where an integer is expected triggers a 422 Unprocessable Entity response. Fix it by correcting the client payload or updating the Pydantic model to accept the actual data types.
Reading the Stack Trace
Here's what each line means:
- "POST /api/items HTTP/1.1" 422 Unprocessable Entity: FastAPI returned a 422 status code because the request body failed Pydantic validation.
- "loc": ["body", "quantity"]: The validation error is on the 'quantity' field in the request body.
- Input should be a valid integer, unable to parse string as an integer: The client sent 'abc' as the quantity value, which cannot be parsed as an integer.
Common Causes
1. Client sending string instead of integer
The frontend sends form data or JSON with string values where the Pydantic model expects integers.
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class ItemCreate(BaseModel):
name: str
quantity: int
price: float
@app.post('/api/items')
async def create_item(item: ItemCreate):
return {'item': item.dict()}
# Client sends: {"name": "Widget", "quantity": "abc", "price": "19.99"}
2. Using wrong type annotation
The model uses int but the data source provides strings that should be coerced. Pydantic v2 strict mode rejects string-to-int coercion.
class ItemCreate(BaseModel):
model_config = {'strict': True}
name: str
quantity: int # Rejects "10" as a string even though it's a valid number
FastAPI turns it into a 422 response, so it never reaches the bugstack SDK as a crash. If it points to a bug in your code, report it where you handle it with bugstack.capture_exception(e); bugstack then works on it like any error the SDK reports.
The Fix
Add a field_validator with mode='before' that coerces string values to integers when possible and raises a clear error message when not. This handles clients that send numeric strings while still rejecting truly invalid input.
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class ItemCreate(BaseModel):
name: str
quantity: int
price: float
@app.post('/api/items')
async def create_item(item: ItemCreate):
return {'item': item.dict()}
from pydantic import BaseModel, field_validator
from fastapi import FastAPI
app = FastAPI()
class ItemCreate(BaseModel):
name: str
quantity: int
price: float
@field_validator('quantity', mode='before')
@classmethod
def parse_quantity(cls, v):
if isinstance(v, str):
if not v.isdigit():
raise ValueError('quantity must be a valid integer')
return int(v)
return v
@app.post('/api/items')
async def create_item(item: ItemCreate):
return {'item': item.model_dump()}
Testing the Fix
import pytest
from httpx import AsyncClient, ASGITransport
from main import app
@pytest.mark.asyncio
async def test_create_item_with_valid_data():
async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client:
response = await client.post('/api/items', json={
'name': 'Widget',
'quantity': 5,
'price': 19.99
})
assert response.status_code == 200
assert response.json()['item']['quantity'] == 5
@pytest.mark.asyncio
async def test_create_item_with_string_quantity():
async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client:
response = await client.post('/api/items', json={
'name': 'Widget',
'quantity': '10',
'price': 19.99
})
assert response.status_code == 200
assert response.json()['item']['quantity'] == 10
@pytest.mark.asyncio
async def test_create_item_with_invalid_quantity():
async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client:
response = await client.post('/api/items', json={
'name': 'Widget',
'quantity': 'abc',
'price': 19.99
})
assert response.status_code == 422
Run your tests:
pytest
Pushing Through CI/CD
git checkout -b fix/fastapi-validation-coercion
git add src/main.py tests/test_items.py
git commit -m "fix: add field_validator to coerce string quantities to integers"
git push origin fix/fastapi-validation-coercion
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: pip install -r requirements.txt
- run: pytest --tb=short
- run: ruff check .
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the error source
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or let bugstack fix it
Set up once, and bugstack takes over the steps from reading the stack trace to proving the fix in an isolated sandbox and opening the pull request. Your CI runs on the pull request, and you set how much merges without you.
Step 1: Install the SDK
pip install bugstack
Step 2: Set it up
# In your main app file, after the FastAPI app is created:
import os
import bugstack
from bugstack.integrations.fastapi import FastAPIMiddleware
bugstack.init(
api_key=os.environ.get("BUGSTACK_API_KEY", ""),
endpoint=os.environ.get("BUGSTACK_ENDPOINT", "https://dashboard.bugstack.ai/api/ingest/sdk"),
)
app.add_middleware(FastAPIMiddleware)
Set BUGSTACK_API_KEY to the key from your dashboard (it starts with bsk_). Then report it where you handle it with bugstack.capture_exception(e).
Step 3: Connect your repository
Sign in at dashboard.bugstack.ai with GitHub, start the 14-day trial, and install the bugstack GitHub App on the repository.
Then, each time the error is reported:
- Your report sends the error and its stack trace
- bugstack reads the files in the stack trace from your repository
- Specialist agents work out the cause and write a small change
- In an isolated sandbox, a test reproduces the error and fails on your current code; with the change it passes, and your other tests still pass
- The change arrives as a pull request with that test and its proof, and your CI runs on it
- On Review, the starting level, you merge it. On Autopilot it merges with green CI and its sandbox proof, checked again at merge.
You review a pull request instead of debugging.
You set how much merges without you.
Get started →Start with a 14-day trial: $50 of credit and a first security audit on us. Then Pro is $100 a month with $100 of usage credit every month. A card is required.
Deploying the Fix (Manual Path)
- Run pytest locally to confirm validation handles both integer and string inputs.
- Open a pull request with the field_validator changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review the validation logic.
- Merge to main and verify the API accepts valid payloads in staging.
Frequently Asked Questions
Ideally fix both. Update the client to send correct types, and add server-side coercion as a safety net for backward compatibility.
Yes. Pydantic v2 is stricter by default. In v1, int fields coerced strings automatically. In v2, you need to use field_validator or set strict=False in the model config.
FastAPI turns it into a 422 response, so it never reaches the bugstack SDK as a crash. If it points to a bug in your code, report it where you handle it with bugstack.capture_exception(e); bugstack then works on it like any error the SDK reports.
bugstack proves it before you see it. In an isolated copy of your repository, with the network cut, it writes a test that reproduces this error and fails on your current code; with the fix the test passes and the rest of your tests still pass. The pull request carries that test and its proof, your CI runs on it, and on Autopilot it merges only with that proof, checked again at merge.
A fix that does not turn the reproduction test green, or that breaks another test, never becomes a pull request. A fix that does is still a pull request, so your CI runs on it, and on Review, the starting level, a person merges it. Undoing a merged fix opens a revert pull request.
Stop fixing Python errors manually.
bugstack catches uncaught server errors, failed deploys and failing CI, works out the cause, and opens a pull request you control.