1

I have a resource called Profile which nests a list of Port resources like so:

{
        "profile": "abcd"
        "ports": [
            {
                "port": "5687"
                "state": "state"
                "protocol": "protocol"
                "direction": "direction"
            }
        ]
 }

The profile key uniquely identifies the Profile resource and the ports key represents the nested list of Port resources. The port key in the Port resource uniquely identifies a port for the given Profile.

The two Resources are modeled like so:

PortModel = api.model("Port", 
    {
        "port": fields.String(required=True),
        "state": fields.String(required=True),
        "protocol": fields.String(),
        "direction": fields.String()
    },
)

ProfileModel = api.model("Profile",
    {
        "profile": fields.String(required=True),
        "ports": fields.List(fields.Nested(PortModel), required=True),
    },
)

The skeleton implementation of the two Resources is given below:

class Profile(Resource):    
    @api.expect(ProfileModel)
    def post(self):
        pass

class PortsList(Resource):
    @api.expect([PortModel])
    def post(self, profile):
        pass

Then the routes are as given below:

api.add_resource(Profile, "api/v1.0/profiles/")
api.add_resource(PortsList, "/api/v1.0/profiles/<profile>/ports")

Question:

When a POST request comes to /api/v1.0/profiles/<profile>/ports with the following body:

[
    {
        "port": "5687"
        "state": "state"
        "protocol": "protocol"
        "direction": "direction"
    }
]

the backend should create the list of Port resources for the given profile.

Similarly, when a POST request comes to api/v1.0/profiles with the following body:

{
    "profile": "abcd"
    "ports": [
        {
            "port": "5687"
            "state": "state"
            "protocol": "protocol"
            "direction": "direction"
        }
    ]
 }

Is it possible for the post method of Profile resource to automatically invoke and reuse the post method of Port resource passing to it the profile which uniquely identifies the Profile resource? If so, do I need to write my own code or the framework has the capability to handle this?

nitin_cherian
  • 6,405
  • 21
  • 76
  • 127

1 Answers1

0

In your use case, does it make sense to create a common Python function to handle the logic of the ports, and call this function from both endpoints?

def handle_ports(profile, ports):
    ... # Process your ports

class Profile(Resource):    
    @api.expect(ProfileModel)
    def post(self):
        handle_ports(
            request.json.get('profile'),
            request.json.get('ports')
        )
        ... # Do additional stuff for this endpoint

class PortsList(Resource):
    @api.expect([PortModel])
    def post(self, profile):
        handle_ports(
            profile,
            request.json.get('ports')
        )