Search code examples
laravelhttpswagger

Swagger not displaying validation error instead it returns HTML code - Laravel 9


I have setup swagger with my projects, end point is working fine if I give correct input, the problem occurs when I start validation by giving wrong parameters, postman is working fine and returning validation error but swagger returns HTML Page.

Swagger Code:

/**      * @OA\Put(      
*      path="/api/admins/{id}/status",      
*      operationId="updateAdminStatus",      
*      tags={"Admin"},      
*      security={ {"sanctum": {} }},      
*      summary="Update admin status",      
*      description="Update an existing admin user's status by ID",      
*      @OA\Parameter(      
*          name="id",      
*          in="path",      
*          required=true,      
*          description="Admin ID",      
*          @OA\Schema(type="integer", format="int32", example=1)      
*      ),      
*      @OA\RequestBody(      
*          required=true,      
*          description="Pass admin data",      
*          @OA\JsonContent(      
*              required={"status"},      
*              @OA\Property(property="status", type="integer", format="int32", example=0)      
*          )      
*      ),      
*      @OA\Response(      
*          response=200,      
*          description="Admin status updated successfully"      
*      ),      
*      @OA\Response(      
*          response=400,      
*          description="Invalid input data"      
*      ),      
*      @OA\Response(      
*          response=401,      
*          description="Unauthenticated"      
*      ),      
*      @OA\Response(      
*          response=404,      
*          description="Admin not found"      
*      ),      
*      @OA\Response(      
*          response=500,      
*          description="Internal server error"      
*      )      
* )      
*/

Validation Part

`$validatedData = $request->validate([
            'status' => 'required|in:0,1'
        ]);
        throw_unless($validatedData);`

Postman Response:

`
{
    "message": "The status field is required.",
    "errors": {
        "status": [
            "The status field is required."
        ]
    }
}`

Swagger Response

enter image description here

I have tried try catch in validation.


Solution

  • Please add @OA\JsonContent() in response body.

     *     @OA\Response(
     *         response=200,
     *         description="success",
     *      @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="invalid data",
     *          @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="internal server error",
     *         @OA\JsonContent()
     *     ),
    

    Try this.