Build Simple REST API with Laravel
REST (Representational State Transfer) is an architectural method of communication that uses HTTP protocol for data exchange. Application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. In short, API can make other applications, whether it’s a mobile apps or something else, can communicate with our application.
In this post I want to share how to create a REST API in Laravel with very simple way.
First create a new project or you can skip this if you already have one.
composer create-project laravel/laravel laravel-api --prefer-dist
Set up your database connection in the .env
and then create migration for some table, in this I will use posts table as an example.
php artisan make:migration create_posts_table
In the posts migration file :
<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug');
$table->string('body');
$table->timestamps();
});
} /**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}}
Run migrate with php artisan migrate
command.
Create some models and controllers
php artisan model Post -c
Write all, show, store, update and destroy function in the controller, in the PostController will be something like this :
Add guarded
or fillable
property into Post model, because in the controller we use mass assignment.
protected $guarded = ['id'];
Modify the routes in api.php
use App\Http\Controllers\PostController;Route::group(['prefix'=>'post'], function () {
Route::get('/', [PostController::class, 'index']);
Route::get('/{id}', [PostController::class, 'show']);
Route::post('/', [PostController::class, 'store']);
Route::put('/{id}', [PostController::class, 'update']);
Route::delete('/{id}', [PostController::class, 'destroy']);
});
Test
We need application like postman or insomnia or something else for testing purpose. You can download postman from this link.
Thats all that I can share in this post. Maybe in the next post I will share about API authentication in Laravel using passport.
Thanks for reading my post, please feel free to leave a comment if you have any suggestions or questions. See ya…
References
1. https://en.wikipedia.org/wiki/API