In this tutorial we will learn How to create a RESTful API using Laravel 8. we will perform create, update, delete and get all posts using API.
what is API ?
An Application Programming Interface enables applications to access data and other external software functionalities. APIs are gaining popularity among developers since they save time and resources. Companies do not need to develop complex systems from scratch.
They can opt to consume data from other existing frameworks. An API is responsible for returning the appropriate response whenever an application sends a request.
Prerequisites
- PHP 7.1 or Higher
- Composer
- MySql
- Laravel 5.6 or Higher
- Postman
Step1: Create a project
To create a new project in laravel run the following command.
create-project laravel/laravel learn-api
Step2: Set up database
create a new database named api_learn and set database configuration in the config file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=api_learn DB_USERNAME=root DB_PASSWORD=
Step3: Create a model
You can create a model using the following command.
php artisan make:model post -m
Step4: Migration
Migration will help you to create a table and define fields into the table, so you will create a migration for the posts table. write down the below code in the up function of the post-migration file
public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('slug'); $table->integer('likes')->nullable(); $table->string('content')->nullable(); $table->timestamps(); }); }
Now run the migration by using php artisan migrate command.
Set fillable variable inside post model file and pass fields of our new created table:
protected $fillable=[ 'title','slug','likes','content' ];
Step5: Setup the Routes
you can create routes individually and also routes can be created by resource. to create by resource class.
Route::resource('post',PostController::class);
Now, let’s check that our created routes are pointed to right? you can check the route list by running php artisan route:list in the command line and it will show you a list of routes available with its information.
Step6: Create Restful API
Now you will need to develop functions that will point to routes and perform create, update, delete, and more functionalities base on our requirements.
Now create a controller for API. here is an example to create a controller using the command
Php artisan make:controller PostController --api
It creates a controller at app/http/controller/PostController.php you can see it in this structure.
Now create API for getting all posts, create, update and delete in this controller
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\post; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //Get all post return post::all(); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //first validate the data $this->validate(request(),[ 'title' => 'required', 'slug' => 'required' ]); // Create a post return post::create($request->all()); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // Show a post return post::find($id); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { //Update a post $post=post::find($id); $post->update($request->all()); return $post; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // Delete a post return post::destroy($id); } }
Testing:
Now you can test API in postman or with any API clients
API for Get all post:
Method: GET API Url: http://127.0.0.1:8000/api/post
API for Create post:
Method: POST API Url: http://127.0.0.1:8000/api/post
Set Header In postman:
And in postman set body:
Now send request to see response
API for get single post by id:
Method: GET API Url: http://127.0.0.1:8000/api/post/4
API for Update post:
Method: PUT API Url: http://127.0.0.1:8000/api/post/2 Body: {title: updatedtitle}
Note: In the body for the update post you need pass key and value of a field that you want to update. and Pass data with JSON format.
API for Delete post:
Method: DELETE API Url: http://127.0.0.1:8000/api/post/3
that’s it you have created All CRUD functions with API.
Here you will get full code for Laravel application : https://github.com/gvtechnolab/RESTful-API-using-Laravel