RESTful API in Laravel web app

Victor Yeo
2 min readOct 31, 2020

--

In this tutorial, we create a Laravel app and learn how to add RESTful API to it. This Laravel app provides two RESTful APIs: http get and http post. In this tutorial, we use Laravel version 8. Command to check Laravel version:

php artisan --version

Now we create the new Laravel app. There are two ways:

composer create-project laravel/laravel <project_name>

or

laravel new <project_name>

We can test the app by running:

php artisan serve --port=8080

We create a .env file that stores the environment variables.

Note: Remember to set the correct database username and password, such as below:

MySQL database settings in .env

We create Laravel database migration php file using php artisan command:

php artisan make:migration create_photos_table

The migration file is in database/migrations

Inspect the file, then use the command below to create the migration tables.

php artisan migrate

If you want to re-create the entire migration database, run this command:

php artisan migrate:refresh

Next, we generate the model that is used in controller.

php artisan make:model Photo

And next, we will create the controller that handles the RESTful api.

php artisan make:controller PhotoController

Then, we add an index function to the controller.

use App\Models\Photo;class PhotoController extends Controller {  public function index() {    $photos = Photo::all();    return $photos;  }}

With the newly created controller, we add the new route to routes/web.php

use App\Http\Controllers\PhotoController;Route::get(‘/photo’, [PhotoController::class, ‘index’]);

Next, we add a store function to the controller.

public function store(Request $request) {  $photo = new Photo;  $photo->url = $request->input(‘url’);  $photo->save();  return $photo;}

Not forgetting, add the route for http post in web.php

Route::post(‘/photo’, [PhotoController::class, ‘store’]);

We can use curl or postman to test the http get and post api.

When testing the http post api, i encounter an HTTP 419 unknown status error. This error happens because Laravel generates a CSRF token for every user session. To overcome the error, go to the file, edit app\Http\middleware\verifycsrftoken.php , add the post api endpoint to it.

protected $except = [  ‘photo’,];

Not forgetting, set the Content-Type to application/json when testing http post api.

The end.

--

--

No responses yet