- Published on
How to integrate an existing RestAPI into Filament
- Authors
-
-
- Name
- Cristian Iosif
- Laravel and FilamentPHP Enthusiast
- X.com
- @X
-
If you're wondering if it is possible to integrate a production ready API into Filament admin panel, well, stop wondering, it is possible using an workaround. You can use a package such as Sushi or Orbit to query your API data using Eloquent models.
# First steps
First of all, to demonstrate this, we will be using a dummy RestAPI. In this example, I am going to use https://dummyapi.online/api/movies. I would start by creating the model, in our API the resource is about movies, so let's make the corresponding model:
1php artisan make:model Movie
# Sushi time
As said in the introduction, we need to use a package that would help us query the model, but not from the database but from an array. To demonstrate this, I chose Caleb's Sushi package.
1composer require calebporzio/sushi
With all these, we can now fetch the data from the API. Let's prepare the model by adding the Sushi trait and the getRows
method that will map the json response to an array.
1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Model; 6use Illuminate\Support\Facades\Http; 7 8class Movie extends Model 9{10 use \Sushi\Sushi;11 12 public function getRows()13 {14 return Http::get('https://dummyapi.online/api/movies')->json();15 }16}
# The Filament juice
Next step, create the Filament resource:
1php artisan make:filament-resource Movie --generate
And basically that's it, you should now see the movies table resource filled with the data from the API and also the edit form prefilled with the data for the corresponding movie.
# Extra
If you wish to persist the changes, you could cache the data from the API call, Sushi can help you with that by adding these to your Movie model:
1class Movie extends Model 2{ 3 use \Sushi\Sushi; 4 5 protected $guarded = []; 6 7 //... 8 9 protected function sushiShouldCache(): true10 {11 return true;12 }13}
Of course, you can take this a step further by talking directly to the API, but you can figure this by your own from this point :)