8

我正在使用L5-Swagger 5.7.* 包(Swagger-php的包装器)并尝试描述 Laravel REST API。所以,我的代码是这样的:

/**
 * @OA\Post(path="/subscribers",
 *     @OA\RequestBody(
 *         @OA\MediaType(
 *            mediaType="application/json",
 *            @OA\Schema(
 *               type="object",
 *               @OA\Property(property="email", type="string")
 *            )
 *        )
 *    ),
 *   @OA\Response(response=201,description="Successful created"),
 *   @OA\Response(response=422, description="Error: Unprocessable Entity")
 * )
 */
public function publicStore(SaveSubscriber $request)
{
    $subscriber = Subscriber::create($request->all());
    return new SubscriberResource($subscriber);
}

但是当我尝试通过招摇面板发送请求时,我得到了代码:

curl -X POST "https://examile.com/api/subscribers" -H "accept: */*" -H "Content-Type: application/json" -H "X-CSRF-TOKEN: " -d "{\"email\":\"bademail\"}"

如您所见,accept 不是 application/json 并且 Laravel 不会将其识别为 AJAX 请求。因此,当我发送错误数据并期望得到 422 实际错误时,我会在“会话”中得到 200 个错误代码。通过 swagger 面板的请求 (XHR) 也被错误地处理,CURL 代码只是为了清楚起见。

另外,我发现在以前的版本中使用了类似的东西:

* @SWG\Post(
*     ...
*     consumes={"multipart/form-data"},
*     produces={"text/plain, application/json"},
*     ...)

但现在它已经过时了。

那么,如果验证失败,如何在不重定向的情况下获取 422 代码?或者可能添加“XMLHttpRequest”标头?在这里做的最好的事情是什么?

4

1 回答 1

11

响应未指定 mimetype。

 @OA\Response(response=201, description="Successful created"),

如果您指定一个 json 响应,swagger-ui 将发送一个Accept: application/json标头。

PS。因为 json 是如此常见 swagger-php 有一个@OA\JsonContent速记,这适用于响应:

@OA\Response(response=201, description="Successful created", @OA\JsonContent()),

和请求主体:

@OA\RequestBody(
  @OA\JsonContent(
    type="object",
    @OA\Property(property="email", type="string")
  )
),
于 2018-11-25T16:36:34.547 回答