什么是PUT和POST方法的REST标准?

问题描述 投票:0回答:1

我正在Laravel中实现API并根据REST标准得到评论我的POST和PUT方法不准确。

我正在使用POST来创建新资源,使用PUT来更新现有资源。看不出问题。

终点:

Route::post('/cities', [
    'uses' => 'CityController@store'
]);

Route::put('/cities/{id}', [
    'uses' => 'CityController@update'
]);

PUTPOST方法:

public function update(Request $request, $id)
{
    $this->validate($request, [
        'name'      => 'required|min:3',
        'latitude'  => 'required|numeric',
        'longitude' => 'required|numeric'
    ]);

    // update model and only pass in the fillable fields
    $this->cityRepository->update(
        $request->only($this->cityRepository->getModel()->fillable), $id
    );

    return $this->cityRepository->show($id);
}

public function store(Request $request)
{
    $this->validate($request, [
        'name'      => 'required|min:3',
        'latitude'  => 'required|numeric',
        'longitude' => 'required|numeric'
    ]);

    $data = $this->cityRepository->create(
        $request->only($this->cityRepository->getModel()->fillable));

    if ($data) {
        $message = self::SUCCESSFULLY_CREATED;
        $code = self::HTTP_CODE_CREATED;
    } else {
        $message = self::UNSUCCESSFULLY_CREATED;
        $code = 409;
    }

    return $this->sendResponse($message, $data, $code);
}

发送回复:

public function sendResponse($message, $result = [], $code = 200)
    {
        $response = [
            'message' => $message,
        ];

        if (!empty($result)) {
            $response['data'] = $result;
        }

        return response()->json($response, $code);
    }

显示方法:

 public function show($id)
    {
        return $this->model->findOrFail($id);
    }
laravel rest api post put
1个回答
0
投票

您可以从store方法而不是SUCCESSFULLY_CREATED返回创建的对象。除此之外代码看起来不错。

看一下https://laravel.com/docs/5.8/controllers#resource-controllers上的表,它对各种CRUD路由有一个相当有用的REST定义:

GET         /photos                 index       photos.index
GET         /photos/create          create      photos.create
POST        /photos                 store       photos.store
GET         /photos/{photo}         show        photos.show
GET         /photos/{photo}/edit    edit        photos.edit
PUT/PATCH   /photos/{photo}         update      photos.update
DELETE      /photos/{photo}         destroy     photos.destroy

这是一个很好的资源,你应该返回HTTP方法:

https://www.restapitutorial.com/lessons/httpmethods.html

© www.soinside.com 2019 - 2024. All rights reserved.