I am trying to create an API for the sendOTP function created in the controller. The package I'm using to do so is DarkaOnLine/L5-Swagger which generates swagger UI based on OpenApi 3.0. I am new to Laravel Swagger API and the problem is with validations. I have 2 fields that are supposed to be validated country_code & mobile. I pass the $request parameter to the LoginRequest to validate the data. Below are my controller and request code.
LoginController
/**
* #OA\POST(
* path="/api/sendLoginOTP",
* operationId="sendLoginOTP",
* tags={"LoginviaOTP"},
* summary="Send Otp to mobile lstest",
* description="Sends Otp to Mobile and Returns mobile number and country code with default country code",
*
* #OA\Parameter(
* name="country_code",
* description="country code",
* required=true,
* in="path",
* #OA\Schema(
* type="string"
* )
* ),
* #OA\Parameter(
* name="mobile",
* description="mobile number",
* required=true,
* in="path",
* #OA\Schema(
* type="integer"
* )
* ),
* #OA\Response(
* response=200,
* description="successful operation"
* ),
* #OA\Response(response=400, description="Bad request"),
* #OA\Response(
* response=401,
* description="Unauthenticated",
* ),
* #OA\Response(response=404, description="Resource Not Found"),
* security={
* {
* "oauth2_security_example": {"write:projects", "read:projects"}
* }
* },
* )
*/
public function sendOTP(LoginRequest $request)
{
return response()->json('Validated');
}
LoginRequest
public function authorize()
{
return true;
}
public function rules()
{
return [
'country_code' => [
'required',
'exists:countries,iso',
'exists:users,country_code',
],
'mobile' => [
'required',
'numeric',
'exists:users,mobile',
],
];
}
Swagger UI
Output I get After Entering Credentials
JSFIDDLE of whole output I am getting
Output am expecting
My problem: whenever I am trying to validate the parameters it's not getting validated. I am not sure where am I going wrong here. Am I not supposed to pass $request to LoginRequest? if not this method then how am I supposed to validate the data provided in the parameters?
I just changed the in value of parameters from path to query and it worked well for me
/**
* #OA\Parameter(
* ....
* in="query",
* ....
* ),
* #OA\Parameter(
* ....
* in="query",
* ....
* ),
*/
Related
I have this a project that is using Laravel for the api and swagger for documentation
I have this method in my login controller:
/**
* Handle an incoming authentication request.
*
*
* #OA\Post(
* tags={"UnAuthorize"},
* path="/login",
* summary="User Login",
* #OA\RequestBody(
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="object",
* ref="#/components/schemas/LoginRequest",
* )
* )
* ),
* #OA\Response(
* response="200",
* description="An example resource",
* #OA\JsonContent(
* type="object",
* #OA\Property(
* format="string",
* default="20d338931e8d6bd9466edeba78ea7dce7c7bc01aa5cc5b4735691c50a2fe3228",
* description="token",
* property="token"
* )
* ),
* #OA\JsonContent(ref="#/components/schemas/UserResource")
* ),
* #OA\Response(response="401", description="fail"),
* )
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
return response()->json(
[
"token" => $request->user()->createToken($request->email)->plainTextToken,
"user" => $request->user();
]
);
}
then, when I run this command: php artisan l5-swagger:generate ,it displays this error:
c:\myproject\vendor\zircote\swagger-php\src\Logger.php:40
36▕ $this->log = function ($entry, $type) {
37▕ if ($entry instanceof Exception) {
38▕ $entry = $entry->getMessage();
39▕ } ➜ 40▕ trigger_error($entry, $type);
41▕ };
42▕ }
When I remove this
#OA\JsonContent(ref="#/components/schemas/UserResource")
it works, but the user data is not displayed, maybe I should only return the token, and make another request with the token to get the information about the logged user. What can I do?, thanks
EDIT:
#OA\Response(
* response="200",
* description="An example resource",
* #OA\JsonContent(
* type="object",
* #OA\Property(
* format="string",
* default="20d338931e8d6bd9466edeba78ea7dce7c7bc01aa5cc5b4735691c50a2fe3228",
* description="token",
* property="token"
* ),
* #OA\Property(
* format="application/json",
* property="user",
* #OA\JsonContent(ref="#/components/schemas/UserResource")
* )
* ),
* )
I tried this, but it shows errors
Pretty close except...
use of 'format' instead of 'type'
you do not have to specify the content type if your property is already wrapped in #OA\JsonContent
you need to be careful with surplus trailing ','; doctrine can be picky with that
Here is my take which does work stand-alone (except for the missing #OA\Info):
<?php
use OpenApi\Annotations\OpenApi as OA;
/**
* #OA\Schema
*/
class LoginRequest{}
/**
* #OA\Schema
*/
class UserResource{}
/**
* Handle an incoming authentication request.
*
*
* #OA\Post(
* tags={"UnAuthorize"},
* path="/login",
* summary="User Login",
* #OA\RequestBody(
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="object",
* ref="#/components/schemas/LoginRequest"
* )
* )
* ),
* #OA\Response(
* response="200",
* description="An example resource",
* #OA\JsonContent(
* type="object",
* #OA\Property(
* type="string",
* default="20d338931e8d6bd9466edeba78ea7dce7c7bc01aa5cc5b4735691c50a2fe3228",
* description="token",
* property="token"
* ),
* #OA\Property(
* property="user",
* ref="#/components/schemas/UserResource"
* )
* )
* ),
* #OA\Response(response="401", description="fail")
* )
*
*/
class Controller {}
The JsonContent you removed should be a property on the first JsonContent I think
I am learning how to use laravel with swagger, and I have this issue:
I have the user controller:
UserController.php
class UserController extends Controller
{
/**
* Shows authenticated user information
*
* #OA\Get(
* tags={"Authorize"},
* path="/user",
* summary="get user detail",
* security={{ "AuthBearer":{} }},
* #OA\Response(
* response="200",
* description="success",
* #OA\JsonContent(
* ref="#/components/schemas/UserResource"
* )
* ),
* #OA\Response(response="401", description="Unauthenticated")
* )
*
* #return \Illuminate\Http\Response
*/
public function user()
{
return new UserResource(auth()->user());
}
}
UserResource.php
/**
* Class UserResource
*
* #OA\Schema(
* #OA\Xml(name="UserResource")
* )
*/
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #OA\Property(format="int64", title="ID", default=1, description="ID", property="id"),
* #OA\Property(format="string", title="name", default="Demo", description="Name", property="name"),
* #OA\Property(format="string", title="username", default="demo", description="Username", property="username"),
* #OA\Property(format="string", title="avatar_path", default="https://via.placeholder.com/640x480.png/0000bb?text=avatar", description="Avatar Path", property="avatar_path")
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'username' => $this->username,
'avatar_path' => $this->avatar_path
];
}
}
this is working fine, but in the swagger docs, the example value for this route is this:
{
"id": 1,
"name": "demo",
"username": "demo",
"avatar_path": "https://via.placeholder.com/640x480.png/0000bb?text=avatar"
}
But when I execute the route in swagger, it returns this:
{
"data": {
"id": 1,
"name": "demo",
"username": "demo",
"avatar_path": "https://via.placeholder.com/640x480.png/0000bb?text=avatar"
}
}
This is wrapped inside a data property, I would like that the example has the same format, how could achieve that? thanks.
You can write in UserResource.php:
/**
* #OA\Schema(
* #OA\Xml(name="UserResource"),
* #OA\Property(property="data", type="array",
* #OA\Items(ref="#/components/schemas/User"))
* ),
* )
*/
And in model User.php
/**
* #OA\Schema(
* #OA\Xml(name="User"),
* #OA\Property(format="int64", title="ID", default=1, description="ID", property="id"),
* #OA\Property(format="string", title="name", default="Demo", description="Name", property="name"),
* #OA\Property(format="string", title="username", default="demo", description="Username", property="username"),
* #OA\Property(format="string", title="avatar_path", default="https://via.placeholder.com/640x480.png/0000bb?text=avatar", description="Avatar Path", property="avatar_path")
* )
*/
darkaonline/l5-swagger: 8.0.2
PHP Version: 7.3.13
zircote/swagger-php: 3.1.0
OS: Windows
I created a Contract ref object.
Now in my ContractController I want to list an array of contracts.
How can I do it?
I got this error Couldn't find constant array when trying to add type=array in OA\Items
/**
* #OA\Info(title="Contract API", version="1")
*/
class ContractController extends Controller
{
/**
* #OA\Post(
* path="/api/v1/contract/list",
* tags={"contact"},
* summary="List Contract",
* operationId="list",
* #OA\Parameter(
* name="keyword",
* in="path",
* description="keyword to search contracts",
* required=false,
* #OA\Schema(
* type="string"
* )
* ),
* #OA\Parameter(
* name="lang_code",
* in="path",
* description="lang_code define language client used",
* required=false,
* #OA\Schema(
* type="string",
* )
* ),
* #OA\Response(
* response=200,
* description="successful",
* #OA\JsonContent(
* #OA\Items(
* type=array, #This is where I got the error
* ref="#/components/schemas/Contract"
* )
* )
* ),
* #OA\Response(
* response=400,
* description="Wrong"
* )
* )
*/
public function list(Request $request)
{
$contracts = Contract::factory()->count(10)->make();
return response()->json([
'message' => 'good',
'contracts' => $contracts
], 200);
}
}
/**
* #OA\Schema(
* description="Contract model",
* type="object",
* title="Contract model"
* )
*/
class Contract extends Model
{
use HasFactory;
/**
* The unique identifier of a product in our catalog.
*
* #var integer
* #OA\Property(format="int64", example=1)
*/
public $id;
/**
* #var string
* #OA\Property(format="string", example="contract 001")
*/
public $contract_title;
}
Use type="array", (with "s) instead of type=array,
I know its late but
Try to use
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="array",
* #OA\Items(
* ref="#/components/schemas/Contract"
* ),
* )
* )
Insead of #OA\JsonContent
I'm using Swagger to do the documentation of the Laravel API's, and sometimes there is also testing apart from POSTMAN, the issue is that the GET methods with parameters do not work Route::get('/searchProduct/{id}','Api\ReportController#getProductsByID');
But if the GET method does not have parameters it works perfectly. In Swagger I realized that when I make the query I don't enter the parameter in {id} but I believe after {id}?id=4
This is my route
My route
Route::get('/searchProduct/{id}','Api\ReportController#getProductsByID');
Result in Swagger
www.x.cl/api/searchProduct/{id}?id=4 //ERROR
How it should work
www.x.cl/api/searchProduct/4
Because in POSTMAN I only change my ID by the number and the search works for me.
This is my controller
/**
* #OA\Get(
* path="/api/searchProduct/{id}",
* summary="Search Product by Status",
* description="Lorem ipsun",
* security={
* {"bearer_token":{}},
* },
* #OA\Parameter(
* name="id",
* in="query",
* description="Buscar por estado",
* required=true,
* ),
* #OA\Response(
* response=200,
* description="OK",
* #OA\MediaType(
* mediaType="application/json",
* )
* ),
* #OA\Response(
* response="default",
* description="Ha ocurrido un error."
* ),
* #OA\Response(
* response="401",
* description="No se ha autenticado, ingrese el token."
* ),
* )
*/
public function getProductsByID($uuid){
$validated = Product::status($uuid);
return ReportResource::collection($validated);
}
Try replacing in="query", with in="path", here :
* #OA\Parameter(
* name="id",
* in="query",
* description="Buscar por estado",
* required=true,
* ),
Query refers to "query string", the set of ampersand-separated key/value pairs that come after ? in the URL.
I am developing an api using Laravel 7 and I use Swagger for API documentation. My issue is that I want to upload images using the Swagger API but it doesn't it only displays [object File] when printing out the images, so I can't upload them to the public folder.
My store method
/**
* Store a newly created Products.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*
* #OA\Post(
* path="/api/products",
* tags={"Product"},
* #OA\Response(response="200", description="Adding a new Product."),
*
* #OA\Parameter(
* name="name[]",
* in="query",
* description="Product Name",
* required=true,
* #OA\Schema(type="array", #OA\Items(type="string")),
* ),
* #OA\Parameter(
* name="images[]",
* in="query",
* description="Product Images",
* required=true,
* #OA\Schema(type="array", #OA\Items(type="file")),
* ),
* * )
* )
*
*/
public function upload(Request $request)
{
$request->validate([
"name" => "required",
"images" => "required",
]);
$images = $request->images;
$product = Product::create([]);
if(! is_dir(public_path("/products")) ){
mkdir(public_path("/products"), 0777);
}
$id = $product->id;
$imageCollection = Collection::wrap($images);
$imageCollection->each(function($image) use ($id){
$basename = Str::random();
$original = $basename . "." . $image->getClientOriginalExtension();
$image->move(public_path("/products"), $original);
ProductMedia::create([
"product_id" => $id,
"image" => "/products/".$original,
]);
});
return Product::where("id", $product->id)->with("productMedia")->get();
}
How can I add images through Swagger API?
Instead param with image, try to do something like this
* #OA\RequestBody(
* required=true,
* #OA\MediaType(
* mediaType="multipart/form-data",
* #OA\Schema(
* #OA\Property(
* description="file to upload",
* property="file",
* type="file",
* ),
* required={"file"}
* )
* )
* ),
more examples here: https://github.com/zircote/swagger-php/blob/master/Examples/petstore.swagger.io/controllers/PetController.php
It looks like you are using the L5 Swagger Package. You may have to figure out how to add an annotation to allow multipart/form-data. Not sure how to configure that through the Package, but here is some more info from from the Swagger File Upload Documentation