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
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 root cause
- 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 in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
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
BugStack tests the endpoint with valid integers, numeric strings, and invalid strings. It verifies correct responses for each case and confirms no existing validations are broken.
All fixes are submitted as pull requests with CI validation. Your team reviews the Pydantic model changes before merging.
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.