Search code examples
karatejsonpathjsonresponse

Karate API json response - How to validate the presence of a key which sometimes come and sometimes not in the API response


I need help in validating the presence of one key in the response. The response of the API looks like -

"persons": [
        {
            "id": "27",
            "source": {
                "personId": 281,
                "emailAddress": "[email protected]",
                "firstName": "Steve"
            }
        },
        {
            "id": "28", 
            "source": {
                "personId": 353,
                "emailAddress": "[email protected]",
                "firstName": "John"
                "LastName" : "Cena"         
            }
        }
    ]
}

I want to assert if the source.LastName appears or not and if it does then it should always hold a string value.

The solution should be generic and it should work for 30 or 40 persons object also down the time, currently I am using karate version 0.9.4 and need a resolution for handling such scenarios.

Thanks in advance !


Solution

  • In the schema "##string" validates that the field can be null or a string.

    Sample Code:

    Feature: Schema validation
    
        Scenario:
            * def resp =
                """
                {
                "persons": [
                        {
                            "id": "27",
                            "source": {
                                "personId": 281,
                                "emailAddress": "[email protected]",
                                "firstName": "Steve"
                            }
                        },
                        {
                            "id": "28", 
                            "source": {
                                "personId": 353,
                                "emailAddress": "[email protected]",
                                "firstName": "John",
                                "LastName" : "Cena"         
                            }
                        }
                    ]
                }
                """
            * def schema = 
            """
                {
                    "id": "#string",
                    "source": {
                        "personId": "#number",
                        "emailAddress": "#string",
                        "firstName": "#string",
                        "LastName": "##string"
                    }
                }
    
            """
            * match each resp.persons == schema