The introduction

We’ve been talking about routing to the controller, processing the data and rendering it to the view, but in modern applications, with the front and back separated, it’s just a matter of writing an interface on the back end.

This installment is about writing restful apis in Laravel to see how easy it can be.

Start with a route

What’s the difference between writing an API and rendering a traditional front-end template page? Without the view, you just need to prepare the data, format it according to the rules, and return it.

Laravel default API route is defined in the routes/api.php file. By default, a resource type API is predefined as follows:

Route::middleware('auth:api')->get('/user'.function (Request $request) {
	return $request->user();
});
Copy the code

Auth: API middleware is invoked to verify the User’s authorization, and if the authorization passes, the declared GET method retrieves the User’s information and returns the User model. This is a very common operation in the previous section, so we won’t go over it.

So this routing file, when was it loaded? In the file app/will/RouteServiceProvider. PHP, look a like this:

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}
Copy the code

The service provider declares that the route uses the API character prefix and calls the API middleware, which is defined in the app/Http/ kernel.php file:

protected $middlewareGroups = [
    'api'= > ['throttle: 60, 1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
Copy the code

$this->namespace usually returns App\Http\Controllers. In order to distinguish the API from other applications, we create an API directory under App /Http/Controller to store all Controllers associated with the API.

The namespace in the mapApiRoutes method in the routeserviceprovider.php file should look like this:

->namespace($this->namespace . '\API')
Copy the code

Again using the Event model as an example, declare a route for a resource type in the routes/api.php file:

Route::resource('/events'.'API\EventsController');
Copy the code

Notice the extra prefix API\ on the namespace, indicating that we are putting the EventController file in the API directory.

User permissions

Let’s also focus on the route declared by default:

Route::middleware('auth:api')->get('/user'.function (Request $request) {
	return $request->user();
});
Copy the code

Note middleware Auth: API, because API requests are stateless and there is no correlation between each request, user permissions are used to differentiate the return of resources. So how do we get user authorization? This is defined in the config/auth.php file.

'guards'= > ['api'= > ['driver'= >'token'.'provider'= >'users'.'hash'= >false,]],Copy the code

This section defines how we will authenticate the user. The default drive token definition file laravel/framework/SRC/Illuminate the frame/Auth/TokenGuard. In PHP. To make a long story short, the default constructor class passes in the following fields:

UserProvider $provider,
Request $request.$inputKey = 'api_token'.$storageKey = 'api_token'.$hash = false
Copy the code

Simply put, this is user authentication using the API_token field of the Users table. Mysql > alter table users; alter table users; alter table users;

php artisan make:migration add_api_token_field_to_users_table --table=users
Copy the code

The first is the migration method up function:

public function up()
{
    Schema::table('users'.function (Blueprint $table) {
    	$table->string('api_token'.60)->unique();
    });
}
Copy the code

There is also the down method used for rollback:

public function down()
{
    Schema::table('users'.function (Blueprint $table) {
    	$table->dropColumn('api_token');
    });
}
Copy the code

These are all routine operations, and we’ve used them N times in the previous chapter. Execute command to migrate database:

php artisan migrate
Copy the code

See the effect

The route is ready, and a GET method is declared inside the route to return user model data. The database table field API_token is also ready. We found a user data in the database table and set the API_token value to 1234 for testing.

Now request a url like this in your browser:

http://www.example.com/api/user?api_token=1234
Copy the code

If there is no exception, a JSON string will be output smoothly,

{
    "id":1."provider":null."provider_id":null."first_name":"Tom"."last_name":"Hanks"."email":"[email protected]"."city":""."state_id":null."zip":"43016"."lat":null."lng":null."timezone":"America\/New_York"."title":"Laravel Developer"."created_at":"The 2020-10-14 17:46:19"."updated_at":"The 2020-10-14 17:46:20"."last_login_at":null."is_admin":0."api_token":"1234"
}
Copy the code

Where does this JSON data come from? Is the user model returned by the $request->user() method within the route, using the toArray() formatting method. For demonstration purposes, many of the fields may differ from reality.

Note in particular that the key password field, as well as the token field, is hidden by default, thanks to the definition of the $hiden attribute in the User model:

protected $hidden = [
	'password'.'remember_token',];Copy the code

These fields are not publicly accessible.

Write in the last

This article introduces how to declare API address, has explained the origin of API from middleware to routing, understand the WAY of API authorization, which can provide convenience for us to customize authorization mode more flexibly. This is all pluggable in Laravel, and our logic code works happily instead.

Happy coding 🙂

I am a @programmer assistant, an original author in the IT field who focuses on programming knowledge and circle dynamics