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?
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")
)
),