python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for Endpoint url URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://example.com', input_type=str]

ID: python/pydantic-validation-error-url-scheme

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-08-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

AnyHttpUrl / HttpUrl types reject non-http(s) schemes. Passing 'ftp://', 'file://', or 'ws://' triggers url_scheme error.

generic

中文

AnyHttpUrl / HttpUrl 类型拒绝非 http(s) 协议。传入 'ftp://'、'file://' 或 'ws://' 会触发 url_scheme 错误。

Workarounds

  1. 95% success
    from pydantic import BaseModel, AnyUrl
    
    class Endpoint(BaseModel):
        url: AnyUrl
  2. 88% success
    from pydantic import BaseModel, HttpUrl, field_validator
    
    class Endpoint(BaseModel):
        url: HttpUrl
    
        @field_validator('url', mode='before')
        @classmethod
        def fix_scheme(cls, v):
            return v.replace('ftp://', 'https://') if isinstance(v, str) else v

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Produces invalid URLs like 'http://ftp://example.com' which fail further validation.

  2. 70% fail

    Loses URL validation entirely; invalid URLs slip through and break HTTP clients downstream.