如何为 swagger-php OpenApi 添加接受 application/json header

How to add accept application/json header for swagger-php OpenApi

我正在使用 L5-Swagger 5.7.* package (wrapper of 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);
}

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

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 代码,错误 "session"。通过 swagger 面板的请求 (XHR) 也被错误地处理,CURL 代码只是为了清楚起见。

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

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

但现在已经过时了。

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

响应未指定 mime 类型。

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

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

PS。因为 json 很常见 swagger-php 有一个 @OA\JsonContent shorthand,这适用于响应:

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

和请求主体:

@OA\RequestBody(
  @OA\JsonContent(
    type="object",
    @OA\Property(property="email", type="string")
  )
),

你可以用这个,我用 Request class, 在文件请求

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
    public function rules()
    {
    return [
        'currentPassword' => 'required',
        'newPassword' => 'required|same:confirmPassword',
        'confirmPassword' => 'required'
    ];
    }
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'errors' => $validator->errors(),
            'status' => true
        ], 422));
    }