Search code examples
python-3.xflaskflask-restfulflask-restplusflask-restx

Dictionary type api.model in flask Restx


I am new to flask restx and trying to create a dict type api.model but I cannot find any example or documentation where it is mentioned, I am not sure if there is any work around to achieve this. Please share your ideas

Here is my data I want to return from the api call

{
    "sandbox-iosxe-recomm-1.cisco.com": {
        "username": "developer", 
        "password": "cisco", 
        "protocol": "ssh",
        "port": 22,
        "os_type": "iosxe"
        },
    "sandbox-iosxr-1.cisco.com": {
        "username": "admin", 
        "password": "cisco", 
        "protocol": "ssh",
        "port": 22,
        "os_type": "iosxr"
}

Here is the api.model schema I was trying to create but this doesnt work obviously as there is a single key and value and trying to figuring out, how to achieve this. I do not want to use List for some reason.

device_model = api.model('Device', {
                         'device': {
                                'username': fields.String(required=True, description='username', default='device username'),
                                'password': fields.String(required=True, description='password', default='device password'),
                                'protocol': fields.String(required=True, description='protocol', default='protocol name'),
                                'port': fields.Integer(required=True, description='port', default='port number'),
                                'os_type': fields.String(required=True, description='os_type', default='device OS type'),
                                }
                              }
                            )

Solution

  • You can use a nested model

    device_nested = api.model(
        "device_nested",
        {
            'username': fields.String(required=True, description='username', default='device username'),
            'password': fields.String(required=True, description='password', default='device password'),
            'protocol': fields.String(required=True, description='protocol', default='protocol name'),
            'port': fields.Integer(required=True, description='port', default='port number'),
            'os_type': fields.String(required=True, description='os_type', default='device OS type'),
        },
    )
    
    device = api.model(
        "device",
        {
            "device": Nested(device_nested),
        },
    )
    

    It should result in

    {
        "device": {
            ...
        }
    }