This repository was archived by the owner on May 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Get Data
Alexandre Nucera edited this page Mar 19, 2015
·
6 revisions
This "decorator" is used to retrieve the data automatically in the request, and send in the object data
to the method. You can see an example in project.py:
from rest_api.API import API
from rest_api.errors import ResponseError, ResponseNotFound
from rest_api.decorators import must_be_connected, get_data
from example.models import Project, User
class ProjectAPI(API):
# ...
# POST /api/1.0/project : add a new project
@must_be_connected
@get_data(["name", "owner_id"])
def method_post_list(self, session, request, data, **kwargs):
try:
owner = User.objects.get(pk=data["owner_id"])
except:
raise ResponseNotFound(details=["Owner not found"])
try:
project = Project.objects.create(name=data["name"], owner=owner)
except Exception as e:
raise ResponseError("Unable to create the project.", details=[str(e)])
return self.response(self.format(project), code=201)
Here, the POST fields "name" and "owner_id" are retrieved and added to a new object. If one of these doesn't exist in the request, an error is directly return to the client:
$> curl -X POST http://127.0.0.1:8000/api/1.0/project
{
"error": "You must provide all mandatory fields.",
"error_code": 400,
"error_details": [
"You must defined: 'name'",
"You must defined: 'owner_id'"
]
}
You can also add a default content :
@get_data(["email", "password", "is_remember"], default={"is_remember": True})
By default, data are retrieved in the data POST request. You can choice to do this in the data GET request instead:
@get_data(["input"], method="GET")