1. Go to this page and download the library: Download ipunkt/laravel-json-api library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
public function boot(ResourceManager $resourceManager)
// define in api version 1 a resource called 'posts'
$resourceManager->version(1)
->define('posts', function (ResourceDefinition $resource) {
$resource->setRepository(PostRepository::class)
->setSerializer(PostSerializer::class);
});
// define in api version 1 a resource called 'posts'
$resourceManager->version(1)
->define('posts', function (ResourceDefinition $resource) {
$resource->setRepository(PostRepository::class)
->setSerializer(PostSerializer::class)
->setRequestHandler(PostRequestHandler::class);
});
class PostSerializer extends \Ipunkt\LaravelJsonApi\Serializers\Serializer
{
/**
* resource type in response, can differ from requesting resource name
* @var string
*/
protected $type = 'posts';
/**
* returns links
*
* @param Model|Post $model
* @return array
*/
public function getLinks($model) : array
{
return [
'comments' => 'https://localhost/api/v1/posts/1/comments',
];
}
/**
* returns attributes for model
*
* @param Model|Post $model
* @return array
*/
protected function attributes($model) : array
{
return [
'title' => $model->title,
'slug' => str_slug($model->title),
'content' => $model->content,
'excerpt' => substr($model->content, 0, 200),
'words' => count(explode(' ', $model->content)), // example to show you can return more than only concrete model attributes
];
}
}
class PostRepository extends \Ipunkt\LaravelJsonApi\Repositories\Repository
{
/**
* default sort criteria, when nothing given (can be empty)
*
* Format: 'fieldName' => 'asc', // or 'desc'
*
* @var array
*/
protected $defaultSortCriterias = [
'publish_datetime' => 'desc'
];
/**
* sort criterias (can be empty)
*
* Format: 'attributeNameInRequest' => 'field_name_in_database'
* Example: 'date' in request will be 'publish_datetime' in sql query
*
* @var array
*/
protected $sortCriterias = [
'date' => 'publish_datetime',
];
/**
* constructor.
* @param Model|Post $post
* @param \Ipunkt\LaravelJsonApi\Repositories\Conditions\ConditionApplier $conditionApplier
*/
public function __construct(Post $post, \Ipunkt\LaravelJsonApi\Repositories\Conditions\ConditionApplier $conditionApplier)
{
$this->model = $post;
$this->conditionApplier = $conditionApplier;
}
}
class PostRequestHandler extends \Ipunkt\LaravelJsonApi\Http\RequestHandlers\DefaultRequestHandler implements NeedsAuthenticatedUser
{
}
if ($request->expectsJson() ||
$request->headers->contains('accept', ApiRequestHandler::CONTENT_TYPE)) {
$error = new JsonApiError($exception->getMessage());
if ($exception->getCode() > 100) {
$error->setCode($exception->getCode());
}
if ($exception instanceof ModelNotFoundException || $exception instanceof NotFoundHttpException) {
$error->setStatusCode(404)
->setTitle('Resource not found');
}
if ($exception instanceof AuthorizationException) {
$error->setStatusCode(403)
->setTitle('Access forbidden');
}
if ($exception instanceof ValidationException) {
$validationErrors = collect();
foreach ($exception->validator->errors()->keys() as $key) {
$validationErrors->push([
'pointer' => $key,
'message' => str_replace('attributes.', '', $exception->validator->errors()->first($key)),
]);
}
$error->setSource($validationErrors);
}
if ($exception instanceof HttpExceptionInterface) {
$error->setStatusCode($exception->getStatusCode());
}
if (app()->environment('local')) {
$error->setException($exception);
}
return response()->json(['errors' => [$error]], $error->getStatusCode());
}
if ($request->expectsJson() ||
$request->headers->contains('accept', ApiRequestHandler::CONTENT_TYPE)) {
$error = new JsonApiError('Unauthenticated');
$error->setStatusCode(401);
return response()->json(['errors' => [$error]], $error->getStatusCode());
}
namespace Tests;
use App\User;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Ipunkt\LaravelJsonApi\Testing\Concerns\ModifiesRequestHeaders;
use Ipunkt\LaravelJsonApi\Testing\Concerns\PreparesRequestBody;
abstract class TestCase extends BaseTestCase
{
use PreparesRequestBody,
ModifiesRequestHeaders;
use CreatesApplication;
/**
* creates a user and logs him in
*
* @return User
*/
protected function createUserAndLogin(): User
{
$user = factory(\App\User::class)->create();
$response = $this->postJson('/public/v1/tokens', $this->createRequestModel('credentials', [
'email' => $user->email,
'password' => 'secret',
]), $this->headers());
$json = $response->decodeResponseJson();
$token = array_get($json, 'data.id');
$this->setToken($token); // you are loggedin
// you can now overwrite all requests headers with calling $this->headers().
return $user;
}
}