_php tips for Making app interface (API) based on Laravel

Source: Internet
Author: User
Tags auth oauth

Pre-preparation

Preface, why and what to do
My surname is white, the program is a small white, but since the freshman contact to programming this wonderful thing, is completely immersed in the process of the world.

This is not, recently started to toss app again, say now develop a app is really easy, only use JavaScript and a little html+css technology can complete. But the backstage of the app is different. Developed the app, want to let the reading data in, then we will go to develop a backstage.

Laravel frame, is my favorite PHP frame anymore, not one. Last year once wrote my personal website with Laravel but rough degree let me very blush, good don't pull, let us go directly to the subject--Install Laravel first!

Basic Environment Configuration

Specific steps to see the document directly laravel5.2 installation

My own environment is WIN10 above installed wampsrver2.5, but here is worth paying attention to, with wampsrver2.5 words, these several places to change. See my notes on this please click on the preview
Tools: Sublime
Browser: Chrome (plugin postman to use)

About APIs

APIs (application Programming Interface, application programming interfaces) are predefined functions designed to provide applications and developers with the ability to access a set of routines based on software or hardware without accessing the source code. Or understand the details of the internal working mechanism.
Note that the API has its specific purpose and we should be aware of what it does. What should be entered when accessing the API. What you should get after you've accessed the API.

At the beginning of the design API, we should pay attention to these 8 points
The content here extracts the blog of the Arrogant God
The follow-up development plan revolves around this. (Really great summary)

1.Restful Design Principles
Naming of 2.API
Security for 3.API
4.API return Data
5. Processing of pictures
6. Returns the hint information
7. Online API Test Documentation
8. At app startup, invoke an initialization API to get the necessary information

Developing APIs with Laravel

I was worried about whether to learn from zero, found the plugin Dingo/api so now to install it!
First of all, it must be downloaded, yes.
In the newly installed Laravel Composer.json add the following content

Then open cmd execution

Composer Update

Add in the providers in the config/app.php

App\providers\oauthserviceprovider::class,
Dingo\api\provider\laravelserviceprovider::class,
Lucadegasperi\oauth2server\storage\fluentstorageserviceprovider::class,
Lucadegasperi\oauth2server\ Oauth2serverserviceprovider::class,


Add in aliases

' Authorizer ' => lucadegasperi\oauth2server\facades\authorizer::class,


Modify the content in the app/http/kernel.php file

protected $middleware = [\lucadegasperi\oauth2server\middleware\oauthexceptionhandlermiddleware::class,
];
protected $routeMiddleware = [
  ' OAuth ' => \lucadegasperi\oauth2server\middleware\oauthmiddleware::class,
  ' Oauth-user ' => \lucadegasperi\oauth2server\middleware\oauthuserownermiddleware::class,
  ' Oauth-client ' => \lucadegasperi\oauth2server\middleware\oauthclientownermiddleware::class,
  ' Check-authorization-params ' => \lucadegasperi\oauth2server\middleware\checkauthcoderequestmiddleware::class,
  ' csrf ' => \app\http\middleware\verifycsrftoken::class,
];


And then execute

PHP artisan vendor:publish 
php artisan Migrate


Add these configurations in the. env file

Api_standards_tree=x
Api_subtype=rest
Api_name=rest
Api_prefix=api
Api_version=v1
Api_conditional_request=true
Api_strict=false
Api_debug=true
Api_default_format=json

modifying app\config\oauth2.php files

' Grant_types ' => ['
  password ' => ['
    class ' => ' league\oauth2\server\grant\passwordgrant ',
    ' Access_token_ttl ' => 604800,
    ' callback ' => ' \app\http\controllers\auth\passwordgrantverifier@verify ',
  ],
],


Create a new service provider under App/providers to create a new oauthserviceprovider.php file with the following contents

namespace App\providers;

Use Dingo\api\auth\auth;
Use Dingo\api\auth\provider\oauth2;
Use Illuminate\support\serviceprovider;

Class Oauthserviceprovider extends serviceprovider
{public
  function boot ()
  {
    $this->app[auth:: Class]->extend (' OAuth ', function ($app) {
      $provider = new OAuth2 ($app [' Oauth2-server.authorizer ']-> Getchecker ());

      $provider->setuserresolver (function ($id) {
        //Logic to return a user by their ID.
      });

      $provider->setclientresolver (function ($id) {
        //Logic to return a client by their ID.
      });

      return $provider
    });

  Public Function Register ()
  {
    //
  }
}


Then open routes.php to add the associated route

//get access_token Route::p ost (' Oauth/access_token ', function () {return RESPONSE::JSO
N (Authorizer::issueaccesstoken ());

});
Create A test user, you don ' t need the If you already have.
   Route::get ('/register ', function () {$user = new app\user ();
   $user->name= "Tester";
   $user->email= "test@test.com";
   $user->password = \illuminate\support\facades\hash::make ("password");
$user->save ();
});

$api = App (' Dingo\api\routing\router ');
Show user info via restful service. $api->version (' v1 ', [' namespace ' => ' app\http\controllers '], function ($API) {$api->get (' Users ', '
  Userscontroller@index ');
$api->get (' Users/{id} ', ' userscontroller@show ');

});
Just a test with auth check.  $api->version (' v1 ', [' Middleware ' => ' api.auth '], function ($API) {$api->get (' Time ', function () {return
  [' Now ' => microtime (), ' Date ' => date (' y-m-d ', Time ())];
});

}); 

Create basecontroller.php and userscontroller.php separately as follows

Basecontroller
namespace App\http\controllers;

Use dingo\api\routing\helpers;
Use Illuminate\routing\controller;

Class Basecontroller extends Controller
{use
  Helpers;
}

Userscontroller
namespace App\http\controllers;

Use App\user;
Use App\http\controllers\controller;

Class Userscontroller extends Basecontroller
{public

  Function index ()
  {return
    user::all ();
  } Public

  function Show ($id)
  {
    $user = User::findorfail ($id);
    Array form return
    $this->response->array ($user->toarray ());
  }



The passwordgrantverifier.php content is then created under app/http/controllers/auth/as follows

namespace App\http\controllers\auth;
Use Illuminate\support\facades\auth;

Class Passwordgrantverifier
{public
  function verify ($username, $password)
  {
     $credentials = [
      ' Email '  => $username,
      ' password ' => $password,
     ];

     if (Auth::once ($credentials)) {return
       auth::user ()->id;
     }

     return false;
  }
}


Open the Oauth_client table of the database add a client data

INSERT into ' oauth_clients ' (' id ', ' secret ', ' name ', ' created_at ', ' Updated_at ') VALUES (' 1 ', ' 2 ', ' Main website ', ' 2016–0 3–13 23:00:00 ', ' 0000–00–00 00:00:00 ');

The following is a happy test, where the API to test is

Add a user

Http://localhost/register

Read all user information

Http://localhost/api/users

Returns only information with a user ID of 4

Http://localhost/api/users/4

Get Access_token

Http://localhost/oauth/access_token

Use token value to get time, token value is correct to return correct value

Http://localhost/api/time

Open Postman

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.