I want to update one of the resources I defined (user) to update his current status (online/offline) and/or location. Therefore I would use a PUT request like this:
PUT http://server/v1/users/12345
Payload
{
"status": 0
}
to set the status offline for example.
Or it could be:
Payload
{
"latitude": 100,
"longitude": 100
}
The backend is based on Laravel/PHP and I respond to this request in my controller:
public function update(Request $request, $userReference) {
// Get payload from request
$bodyContent = json_decode($request->getContent(), true);
$userReference = $userReference;
// Update the user location
$updateResponderLocationCommand = new UpdateResponderLocationCommand($bodyContent);
$this->commandBus->execute($updateResponderLocationCommand);
$response = [
'userReference' => $userReference
];
return $this->setStatusCode(201)->respond($response);
}
This controller uses a command system I integrated that will trigger the task of doing the update.
My questions are, where I struggle:
PUT http://server/v1/user/100
and by having keywords in the payload and a select switch - approach within the controller a differentiation between tasks to be executed upon? action
property on your json object
that corresponds to the function that should take place. Lets have a look at that:
public function update(....){
switch($request->get('action'))
{
case 'location':
//execute the command here
break;
case 'status':
//execute the command here
break;
}
}
In this way, we can make sure that our commands
are dispatched according to our actions. This is the method that I prefer.
Regarding the whole put vs post - there's no reason to do another write-up as this question thread here has the best breakdown and explanation by far.
You should refer back to the link in #2. When creating a resource, you should use PUT
. This makes sure that the request is idempotent and will not be duplicated (client's hung, server bottlenecked, etc).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.