Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm use L5-Swagger 5.7.* package (wrapper of Swagger-php) and tried describe Laravel REST API. So, my code like this:

/**
 * @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);
}

But when I try send request via swagger panel I get code:

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

As you can see, accept is not application/json and Laravel doesn't identify this as an AJAX request. So, when I send wrong data and expect to get 422 with errors in real I get 200 code with errors in "session". Request (XHR) through the swagger panel is also processed incorrectly, CURL code just for clarity.

Also, I found that in the previous version was used something like:

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

But now it's already out of date.

So, how get 422 code without redirect if validation fails? Or maybe add 'XMLHttpRequest' header? What is the best thing to do here?

like image 522
Nikolay Votintsev Avatar asked Nov 06 '18 08:11

Nikolay Votintsev


People also ask

How do you get the request body required in swagger?

requestBody, content and Media Types content lists the media types consumed by the operation (such as application/json ) and specifies the schema for each media type. Request bodies are optional by default. To mark the body as required, use required: true .


1 Answers

The response(s) didn't specify a mimetype.

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

If you specify a json response, swagger-ui will send an Accept: application/json header.

PS. Because json is so common swagger-php has a @OA\JsonContent shorthand, this works for the response:

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

and the requestbody:

@OA\RequestBody(
  @OA\JsonContent(
    type="object",
    @OA\Property(property="email", type="string")
  )
),
like image 102
Bob Fanger Avatar answered Sep 18 '22 13:09

Bob Fanger