nazrulworld / fhir.resources

FHIR Resources https://www.hl7.org/fhir/resourcelist.html
https://pypi.org/project/fhir.resources/
Other
372 stars 104 forks source link

Add the ability to map pydantic validation errors to proper FHIR error locations #50

Open apollo13 opened 3 years ago

apollo13 commented 3 years ago

Description

I think it would be great if it where possible to map pydantic validation errors to proper fhir locations for `OperationOutcome' https://hl7.org/fhir/STU3/operationoutcome.html#loc

Do you have some thoughts/guidance on that. I might try to implement something like that.

nazrulworld commented 3 years ago

You are more than welcome to do try and share your thoughts

apollo13 commented 3 years ago

I am currently using this:

def pydantic_loc_to_xpath(location_path):
    result = ""
    for loc in location_path:
        if loc == "__root__":
            continue
        if isinstance(loc, int):
            result += f"[{loc}]"
        else:
            result += f"/f:{loc}"

    return result

def pydantic_error_to_operation_issue(error):
    loc = pydantic_loc_to_xpath(error["loc"])
    code = "required" if error["type"] == "value_error.missing" else "invalid"
    return {
        "severity": "error",
        "code": code,
        "location": [loc],
        "diagnostics": error["msg"],
    }

It seems to work fine and generates response ala:

        {
            "severity": "error",
            "code": "required",
            "diagnostics": "field required",
            "location": ["/f:fhirVersion"],
        },
        {
            "severity": "error",
            "code": "invalid",
            "diagnostics": "value is not a valid integer",
            "location": ["/f:contact[1]/f:telecom[0]/f:rank"],
        },
        {
            "severity": "error",
            "code": "invalid",
            "diagnostics": "invalid datetime format",
            "location": ["/f:date"],
        },

Granted, it might not be perfect but it already looks rather nice.