Build APIs in Laravel With the Restify Package

https://laravelnews.imgix.net/images/laravel-restify.png?ixlib=php-3.3.1

Laravel Restify is a package to make a powerful JSON:API-compatible Rest API with Laravel. After installing the package and following the setup guide, you can get started quickly using the repository CLI:

1php artisan restify:repository Dream --all

The repository is the core of this package. The example command above would generate a blank repository that you could add fields to, like the following example:

1namespace App\Restify;

2 

3use App\Models\Dream;

4use Binaryk\LaravelRestify\Http\Requests\RestifyRequest;

5 

6class DreamRepository extends Repository

7{

8 public static string $model = Dream::class;

9 

10 public function fields(RestifyRequest $request): array

11 {

12 return [

13 id(),

14 field('title')->required(),

15 field('description'),

16 field('image')->image(),

17 ];

18 }

19}

If you don’t define the $model property, Restify can guess based on the repository class name (i.e., DreamRepository would be the Dream model).

Here’s an example of the built-in UserRepository class (you would want to protect this in a real app) that will return an API response in JSON API format:

1GET: /api/restify/users?perPage=10&page=2

2{

3 "meta": {

4 "current_page": 1,

5 "from": 1,

6 "last_page": 1,

7 "path": "http://localhost:8000/api/restify/users",

8 "per_page": 15,

9 "to": 1,

10 "total": 1

11 },

12 "links": {

13 "first": "http://localhost:8000/api/restify/users?page=1",

14 "next": null,

15 "path": "http://localhost:8000/api/restify/users",

16 "prev": null,

17 "filters": "/api/restify/users/filters"

18 },

19 "data": [

20 {

21 "id": "1",

22 "type": "users",

23 "attributes": {

24 "name": "Paul Redmond",

25 "email": "paul@example.com"

26 }

27 }

28 ]

29}

This package also walks you through the authentication process, advanced filtering, and more!

Learn More

To get started, I recommend watching the Restify Course, which has 24 lessons on using Restify to build an API with Laravel. You can also read the official documentation to install this package and start using it in your applications. Finally, you can see the source code and contribute on GitHub at BinarCode/laravel-restify.

Laravel News