api.add_resource
时间: 2024-05-08 17:16:41 浏览: 23
Api.add_resource is a method used in Flask-RESTful to add resources to the API. It takes two arguments: the resource class and the URL endpoint to map it to.
For example, suppose we have a resource class called "Item" and we want to map it to the URL endpoint "/items". We would use the following code:
```
from flask_restful import Api, Resource
class Item(Resource):
def get(self, item_id):
# code to retrieve item with given ID
pass
def post(self):
# code to create a new item
pass
def put(self, item_id):
# code to update item with given ID
pass
def delete(self, item_id):
# code to delete item with given ID
pass
api = Api()
api.add_resource(Item, '/items', '/items/<int:item_id>')
```
In this example, we define a resource class called "Item" with methods to handle GET, POST, PUT, and DELETE requests. We then create an instance of the Flask-RESTful API and use the `add_resource` method to map the "Item" resource to the "/items" endpoint. We also include a second URL rule to handle requests with a specific item ID.
The `add_resource` method can be called multiple times to add additional resources to the API.