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
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 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",
* ....
* ),
*/
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 want to uplaod a file in swagger-php in the json requestBody How can upload with the help of swagger anonations
Trying from lot of hours but not luck how can send and file in application/json array Can you help if any information about this so then i will solve my problem i have not concept about this
when this code generate in the terminal also not have any error and not shown in the request body in the swagger ui
/**
* #OA\Post(
* path="/products/save",
* tags={"Product"},
* summary="Post bulk products",
* description="Return bulk products",
* #OA\RequestBody(
* required=true,
* description="Bulk products Body",
* #OA\JsonContent(
* #OA\Property(
* property="products",
* #OA\Items(
* #OA\Property(property="first_name", type="string"),
* #OA\Property(property="last_name", type="string"),
* #OA\Property(property="email", type="string"),
* #OA\Property(property="phone", type="string"),
* #OA\Property(property="resume", type="string", format="base64"),
* ),
* )
* )
* ),
* )
*/
I want to this type of swagger-ui body so that user can fill attribut and
the resume add in base64 format
{
"products": [
{
"first_name": "string",
"last_name": "string",
"email": "string",
"phone": "string",
"resume": "string" ==> here i will send base64 format of resume file
}
]
}
``
You may use #OA\Property(property="file", type="string", format="binary"), to define a file property:
/**
* #OA\Schema(
* schema="ProductRequest",
* required={"products"},
* #OA\Property(
* property="products",
* type="array",
* #OA\Items(
* #OA\Property(property="first_name", type="string"),
* #OA\Property(property="last_name", type="string"),
* #OA\Property(property="email", type="string"),
* #OA\Property(property="phone", type="string"),
* #OA\Property(property="resume", type="string", format="binary"),
* ),
* )
* )
*/
Then you have to set a media type on your RequestBody using #OA\MediaType:
/**
* #OA\RequestBody(
* request="Product",
* required=true,
* description="Bulk products Body",
* #OA\MediaType(
* mediaType="multipart/form-data",
* #OA\Schema(ref="#/components/schemas/ProductRequest")
* )
* )
*/
And finally on your #OA\Post:
/**
* #OA\Post(
* path="/products/save",
* tags={"Product"},
* summary="Post bulk products",
* description="Return bulk products",
* #OA\RequestBody(ref="#/components/requestBodies/Product"),
* #OA\Response(response=200, ref="#/components/responses/Product")
* )
*/
See also Swagger docs on File data type and File upload for more info.
Update: If you don't want separate declarations just merge them like this:
/**
* #OA\Post(
* path="/products/save",
* tags={"Product"},
* summary="Post bulk products",
* description="Return bulk products",
* #OA\RequestBody(
* required=true,
* description="Bulk products Body",
* #OA\MediaType(
* mediaType="multipart/form-data",
* #OA\Schema(
* #OA\Property(
* property="products",
* type="array",
* #OA\Items(
* #OA\Property(property="first_name", type="string"),
* #OA\Property(property="last_name", type="string"),
* #OA\Property(property="email", type="string"),
* #OA\Property(property="phone", type="string"),
* #OA\Property(property="resume", type="string", format="binary"),
* )
* )
* )
* )
* )
* )
*/
You may also want an approach with PHP classes
So you can define a model like that:
/**
* #OA\Schema(
* schema="User",
* required={"first_name", "last_name" // and so on}
* )
*/
class User
{
/**
* #OA\Property(type="string")
*/
public $first_name;
/**
* #OA\Property(type="string")
*/
public $last_name;
// add your other fields bellow
}
after you can define for example the body of a POST request as follows:
<?php
/**
* #OA\Schema(
* schema="CreateUsers",
* required={"users"}
* )
*/
class CreateUsers
{
/**
* #var array
* #OA\Property(ref="#/components/schemas/User")
*/
public $users;
}
And lastly create the your Request in your documentation for example:
/**
* #OA\Post(
* path="YOUR ROUTE URL",
* operationId="createUsers",
* tags={"Users"},
* #OA\RequestBody(
* required=true,
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(ref="#/components/schemas/CreateUsers")
* )
* ),
* summary="Create a collection of users",
* description="Create a collection of users"
* )
**/
EDIT 1:
If you want a request that have a file to the request body you way do:
/**
* #OA\Post(
* path="YOUR ROUTE URL",
* operationId="createUsers",
* tags={"Users"},
* #OA\RequestBody(
* required=true,
* #OA\MediaType(
* mediaType="multipart/form-data", // here we need to change from "application/json" to "multipart/form-data" in order to make our file visible
* #OA\Schema(ref="#/components/schemas/CreateUsers")
* )
* ),
* summary="Create a collection of users",
* description="Create a collection of users"
* )
**/
And make your field in your PHP class:
/**
* #OA\Schema(
* schema="User",
* required={"first_name", "last_name", "file" // and so on}
* )
*/
class User
{
/**
* #OA\Property(type="string")
*/
public $first_name;
/**
* #OA\Property(type="string")
*/
public $last_name;
/**
* #OA\Property(description="file to upload", type="string", format="file")
*/
public $file;
// add your other fields bellow
}
You can see an example here: swagger-php/Examples/petstore.swagger.io/controllers/PetController.php