Product How it works Features Security What is bugstack? SDKs JavaScript SDK Python SDK Go SDK Ruby SDK Docs Pricing Blog Book a demo
Log In Get started
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

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.

Get started →

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 error source
  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

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:

  1. Your report sends the error and its stack trace
  2. bugstack reads the files in the stack trace from your repository
  3. Specialist agents work out the cause and write a small change
  4. 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
  5. The change arrives as a pull request with that test and its proof, and your CI runs on it
  6. 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)

  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

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.