How to create simple REST api in laravel 5?

Shahjalal
Oceanize Lab Geeks
Published in
4 min readNov 13, 2018

In this article I would like to share you how to build simple REST api in laravel 5. Here i will share with you create basic and simple resource api route with json response. you can simply use with your project, So we need to make basic setup for our application.

In this article i will create posts table and create rest api of posts with resource route. Here i also give screen shot for all resource route with response, so you can check response for GET, POST, PUT and DELETE for list, create, update and delete. So let’s just follow bellow step and you will get best api platform.

Step 1: Install laravel 5 project.

We are going to start new laravel project from scratch. So we need to get fresh laravel project and make laravel project using this command. Open the terminal and run the command bellow

composer create-project--prefer-dist laravel/laravel api_make

Step 2: Create table and Modal Ex(create Post table model)

In this step we need to create table using migration for post table. The command is

php artisan make:migration create_posts_table

After this command you get file in this directory `database/migration/…create_post_table`.
Open this file and put this source code this file

<?phpuse Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{/*** Run the migrations.
*
* @return void
*/
public function up(){Schema::create(‘posts’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘title’);
$table->integer(‘is_delete’)->default(‘1’);
$table->longText(‘body’);
$table->timestamps();
});
}/**
* Reverse the migrations.
*
* @return void
*/
public function down(){
Schema::dropIfExists(‘posts’);
}
}

After create “posts” table you should create model for posts, so first create file in this path app/Post.php and put bellow content in Post.php file:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Post extends Model{protected $fillable = [‘title’, ‘body’];}

Step 4: In this step, we have create new controller as APIBaseController and PostAPIController, APIBaseController extend all api controller. i created new folder “API” in Controllers folder because we will make individual APIs controller, So let’s make both controller:

APIBaseController.php

<?phpnamespace App\Http\Controllers\API;use Illuminate\Http\Request;use App\Http\Controllers\Controller as Controller;class APIBaseController extends Controller{public function sendResponse($result, $message){$response = [‘success’ => true,‘data’ => $result,‘message’ => $message,];return response()->json($response, 200);}public function sendError($error, $errorMessages = [], $code = 404){$response = [‘success’ => false,‘message’ => $error,];if(!empty($errorMessages)){$response[‘data’] = $errorMessages;}return response()->json($response, $code);}}

PostAPIController ::

<?phpnamespace App\Http\Controllers\API;use Illuminate\Http\Request;use App\Http\Controllers\API\APIBaseController as APIBaseController;use App\Post;use Validator;class PostAPIController extends APIBaseController{/*** Display a listing of the resource.** @return \Illuminate\Http\Response*/public function index(){$posts = Post::all();return $this->sendResponse($posts->toArray(), ‘Posts retrieved successfully.’);}/*** Store a newly created resource in storage.** @param \Illuminate\Http\Request $request* @return \Illuminate\Http\Response*/public function store(Request $request){$input = $request->all();$validator = Validator::make($input, [‘title’ => ‘required’,‘body’ => ‘required’]);if($validator->fails()){return $this->sendError(‘Validation Error.’, $validator->errors());}$post = Post::create($input);return $this->sendResponse($post->toArray(), ‘Post created successfully.’);}/*** Display the specified resource.** @param int $id* @return \Illuminate\Http\Response*/public function show($id){$post = Post::find($id);if (is_null($post)) {return $this->sendError(‘Post not found.’);}return $this->sendResponse($post->toArray(), ‘Post retrieved successfully.’);}/*** Update the specified resource in storage.** @param \Illuminate\Http\Request $request* @param int $id* @return \Illuminate\Http\Response*/public function update(Request $request, $id){$input = $request->all();$validator = Validator::make($input, [‘title’ => ‘required’,‘body’ => ‘required’,]);if($validator->fails()){return $this->sendError(‘Validation Error.’, $validator->errors());}$post = Post::find($id);if (is_null($post)) {return $this->sendError(‘Post not found.’);}$post->title = $input[‘title’];$post->body = $input[‘body’];$post->save();return $this->sendResponse($post->toArray(), ‘Post updated successfully.’);}/*** Remove the specified resource from storage.** @param int $id* @return \Illuminate\Http\Response*/public function destroy($id){$post = Post::find($id);if (is_null($post)) {return $this->sendError(‘Post not found.’);}Post::where(‘id’, $post->id)->update([‘is_delete’=>’0']);return $this->sendResponse($id, ‘Tag deleted successfully.’);}}

Step 4 : In step four we should create resource routes for list, create, update and delete. so we open your routes/api.php file and put the code following api.php.

routes/api.php

<?phpuse Illuminate\Http\Request;/*|--------------------------------------------------------------------------| API Routes|--------------------------------------------------------------------------|| Here is where you can register API routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| is assigned the "api" middleware group. Enjoy building your API!|*/Route::resource('posts', 'API\PostAPIController');

1. List: GET, URL:http://localhost:8080/api/posts

2. Create: POST, URL:http://localhost:8080/api/posts

3. Show: GET, URL:http://localhost:8080/api/posts/{id}

4. Update: PUT, URL:http://localhost:8080/api/posts/{id}

In here we use port 8080. In your request you will use your own port.

=> List: GET, URL:http://localhost:8080/api/posts

Now I give you screen short of postman request

Create: POST, URL:http://localhost:8080/api/posts

Show: GET, URL:http://localhost:8080/api/posts/{id}

Update: PUT, URL:http://localhost:8080/api/posts/{id}

Delete: DELETE, URL:http://localhost:8080/api/posts/{id}

--

--