Laravel Api Development Series - Use of Dingo API

Keywords: PHP Laravel JSON github

Source code

Using Dingo Api

The database used in this paper is the same as the basic chapter, so it will not be repeated.

Initialization

install

$ composer require dingo/api:1.0.x@dev

register

/config/app.php
'providers' => [
    Dingo\Api\Provider\LaravelServiceProvider::class,
],

In order to be able to customize the configuration, you first need to execute

$ php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
Copied File [/vendor/dingo/api/config/api.php] To [/config/api.php]
Publishing complete.

You can see that there are more api.php configuration files, we can configure them in. env, some common configuration items:

/.env
API_STANDARDS_TREE=vnd  # vnd for public and commercial projects
API_SUBTYPE=api-demo  # Project abbreviation
API_PREFIX=api  # prefix
API_VERSION=v1  # Version number used when no version is provided
API_NAME="Laravel Api Demo"  # Use API Blueprint command to generate documents
API_STRICT=false # Strict mode requires clients to send Accept headers instead of the default version specified in the configuration file, which means that you can't browse the API through a Web browser.
API_DEFAULT_FORMAT=json 
API_DEBUG=true # Open debug mode

Create a basic endpoint (what routes are called in the api) to test whether the configuration is successful

/routes/api.php
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {

    $api->get('test', function () {
        return 'It is ok';
    });

});

Visit / api/test and return it as ok.

Use

Dingo's usage is similar to, or even simpler than, previous custom api s. First define the routing

/routes/api.php
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {

    $api->group(['namespace' => 'App\Api\Controllers'], function ($api) {
        $api->resource('lessons','LessonController');
    });

});

If you want to view routes, you need to use

$ php artisan api:routes

Create Controller - You need to use Helpers trait.

/app/Api/Controllers/LessonController.php
<?php
namespace App\Api\Controllers;

use App\Api\Transformers\LessonTransformer;
use App\Http\Controllers\Controller;
use App\Lesson;
use Dingo\Api\Routing\Helpers;

class LessonController extends Controller
{    
    use Helpers;

    public function index()
    {    
        $lessons = Lesson::all();
        // Collection is used to respond to a collection while binding a Transformer to format data
        return $this->collection($lessons, new LessonTransformer());
    }

    public function show($id)
    {    
        // Although we are not returning json, dingo will automatically convert
        return Lesson::findOrFail($id);
    }
}

Create the corresponding Lesson Transformer

/app/Api/Transformers/LessonTransformer.php
<?php
namespace App\Api\Transformers;

use App\Lesson;
use League\Fractal\TransformerAbstract;

class LessonTransformer extends TransformerAbstract
{
    public function transform(Lesson $lesson)
    {
        return [
            'title'   => $lesson['title'],
            'content' => $lesson['body'],
            'is_free' => (bool) $lesson['free']
        ];
    }
}

Visit api/lessons/3 and the results are as follows

As you can see, Dingo automatically converts the response data into json, but we still need to format it.

public function show($id)
{    
    $lesson = Lesson::findOrFail($id);
    return $this->response->item($lesson, new LessonTransformer());
}

Now you can get the formatted data

Like Laravel, paging can also be used

public function index()
{    
    $lessons = Lesson::paginate(15);
    return $this->response->paginator($lessons, new LessonTransformer());
}

15 pieces of information and page information will be returned

When a request goes wrong, Dingo automatically handles it for us.

You can also customize

public function show($id)
{    
    $lesson = Lesson::find($id);
    if(!$lesson){
        return $this->response->errorNotFound("FALSE id");
    }
    return $this->response->item($lesson, new LessonTransformer());
}

give the result as follows

Combining simple authentication

We can add our own authentication functions to Api, such as HTTP basic authentication. First, create a test user

$ php artisan tinker
>>> $user = new \App\User();
>>> $user->name = "zen"
>>> $user->email = "ihuangmx@qq.com"
>>> $user->password = bcrypt("123456")
>>> $user->save()
=> true

Add Laravel's own middleware to the controller

public function __construct()
{
    $this->middleware('auth.basic');
}

Now you will be prompted to enter a username and password when accessing, where the username refers to the mailbox.

Posted by Weedpacket on Mon, 07 Jan 2019 22:03:09 -0800