How It Works Features Pricing Blog
Log In Start Free Trial
FastAPI · Python

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

INFO: 127.0.0.1:52340 - "POST /api/items HTTP/1.1" 422 Unprocessable Entity { "detail": [ { "type": "int_parsing", "loc": ["body", "quantity"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc", "url": "https://errors.pydantic.dev/2.5/v/int_parsing" } ] } Traceback (most recent call last): File "/app/venv/lib/python3.11/site-packages/pydantic/main.py", line 164, in __init__ self.__pydantic_validator__.validate_python(data) pydantic_core._pydantic_core.ValidationError: 1 validation error for ItemCreate quantity Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str]

Here's what each line means:

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.

Before (broken)
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()}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run pytest locally to confirm validation handles both integer and string inputs.
  2. Open a pull request with the field_validator changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review the validation logic.
  5. 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.