Dictionary type api.model in flask Restx

803 Views Asked by At

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'),
                                }
                              }
                            )
1

There are 1 best solutions below

3
Ammar Aslam On BEST ANSWER

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": {
        ...
    }
}