Responses
OpenAPI specifications can describe the responses of an API by documenting their schema and providing examples. Laradoc makes it easy by automatically identifying common Laravel response objects and running your HTTP tests.
Response types
Through analyzing your source code, Laradoc creates documentation for your API endpoint responses.
It currently supports the following types of responses:
-
JsonResource
responses -
AnonymousResourceCollection
responses - Responses created with
response()->make(...)
,response()->json(...)
,response()->noContent()
- Manually constructed
new JsonResponse
andnew Response
objects -
LengthAwarePaginator
ofJsonResource
items
JsonResource response
Laradoc understands the schema of your JsonResource
responses if you're returning the following field types in the toArray()
method of the resource:
- Nested
JsonResource
return [
'user' => new UserResource($this->user),
];
- Conditional nested
JsonResource
return [
'user' => new UserResource($this->whenLoaded('user')),
];
- Arrays
return [
'id' => $this->id,
'organisation' => [
'type' => $this->organisation_type,
'name' => $this->organisation_name,
],
];
- Model attributes (with or without
resource
)
return [
'id' => $this->id,
'email' => $this->resource->email,
];
For fields that are model attributes, Laradoc retrieves property types accessed through $this
or $this->resource
from corresponding model attributes.
Infering model attribute types requires the doctrine/dbal
package.
By default, Laradoc searches for a model in the App\Models
namespace based on the resource name. Before the search, the resource name is converted to a singular form (e.g., UsersResource
becomes User
).
If you have custom models namespaces, you can manually specify the name of the model by adding a PHPDoc to the resource class. This can be achieved by documenting the $resource
property type or defining the model as a @mixin
.
use App\Entities\User;
/**
* @mixin User
*/
class UserResource extends JsonResource
{
public function toArray
{
return [
'id' => $this->id,
'email' => $this->email,
// ...
];
}
}
LengthAwarePaginator response
If your controller returns a paginated collection of JsonResource
, you need to add a PHPDoc like so:
/**
* List users.
*
* @return AnonymousResourceCollection<LengthAwarePaginator<UserResource>>
*/
public function index(Request $request)
{
return UserResource::collection(User::paginate());
}
Response examples
Once Laradoc has inferred the types of your response fields, it uses your project's tests to generate response examples. By automatically capturing transmitted data in test responses, Laradoc ensures that the generated responses accurately reflect the real-world responses of your API.
Without tests in your project, Laradoc cannot provide real-world response examples and will generate less relevant examples based solely on their types.