Understanding and configuring resourceful routing

The following table shows the method of our previously created classes that we want to be executed for each combination of HTTP verb and scope:

HTTP verb

Scope

Class and method

GET

Collection of notifications

NotificationListResource.get

GET

Notification

NotificationResource.get

POST

Collection of notifications

NotificationListResource.post

PATCH

Notification

NotificationResource.patch

DELETE

Notification

NotificationResource.delete

GET

Collection of notification categories

NotificationCategoryListResource.get

GET

Notification category

NotificationCategoryResource.get

POST

Collection of notification categories

NotificationCategoryListResource.post

PATCH

Notification category

NotificationCategoryResource.patch

DELETE

Notification category

NotificationCategoryResource.delete

If the request results in the invocation of a resource with an unsupported HTTP method, Flask-RESTful will return a response with the HTTP 405 Method Not Allowed status code.

We must make the necessary resource routing configurations to call the appropriate methods and pass them all the necessary arguments by defining URL rules. The following lines configure the resource routing for the service. Open the previously created views.py file within the service folder and add the following code after the last line. The code file for the sample is included in the restful_python_2_02_01 folder, in the Flask01/service/views.py file:

service.add_resource(NotificationCategoryListResource,  
    '/notification_categories/') 
service.add_resource(NotificationCategoryResource,  
    '/notification_categories/<int:id>') 
service.add_resource(NotificationListResource,  
    '/notifications/') 
service.add_resource(NotificationResource,  
    '/notifications/<int:id>')

Each call to the service.add_resource method routes a URL to a resource; specifically, to one of the previously declared subclasses of the flask_restful.Resource superclass. Whenever there is a request to the API, and the URL matches one of the URLs specified in the service.add_resource method, Flask will call the method that matches the HTTP verb in the request for the specified class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.85