Table of Contents
Making API interface based on laravel
Home PHP Framework Laravel Making API interface based on laravel

Making API interface based on laravel

May 28, 2020 pm 04:03 PM
api

Making API interface based on laravel

About API

##API (Application Programming Interface, application programming interface) is some Predefined functions whose purpose is to provide applications and developers with the ability to access a set of routines based on a piece of software or hardware without having to access the source code or understand the details of the inner workings.

It should be noted that API has its specific purpose, and we should know what it does. What should be entered when accessing the API. What should you get after accessing the API.

When starting to design the API, we should pay attention to these 8 points

The subsequent development plan will revolve around this.

1.Restful design principles

2.API naming
3.API security
4.API return data
5.Picture processing
6.Return Prompt information
7. Online API test document
8. When the app starts, call an initialization API to obtain the necessary information

Develop API with laravel

Just when I was worried about whether to start learning from scratch, I found this plug-in dingo/api, so let’s install it now!

First of all, it must be downloaded correctly
Add the following content to the newly installed laravel composer.json

Then open cmd and execute

composer update

Add

1

2

3

4

App\Providers\OAuthServiceProvider::class,

Dingo\Api\Provider\LaravelServiceProvider::class,

LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,

LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,

Copy after login
to providers in config/app.php and add

1

'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class,

Copy after login
to aliases to modify app/ The content in the Http/Kernel.php file

1

2

3

4

5

6

7

8

9

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,

];

Copy after login
Then execute

php artisan vendor:publish

php artisan migrate

Add these configurations in the .env file

1

2

3

4

5

6

7

8

9

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

Copy after login

Modify the app\config\oauth2.php file

1

2

3

4

5

6

7

'grant_types' => [

  'password' => [

    'class' => 'League\OAuth2\Server\Grant\PasswordGrant',

    'access_token_ttl' => 604800,

    'callback' => '\App\Http\Controllers\Auth\PasswordGrantVerifier@verify',

  ],

],

Copy after login
Create a new service provider. Create a new OAuthServiceProvider.php file under app/Providers with the following content

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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()

  {

    //

  }

}

Copy after login
Then open it Add relevant routes to routes.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

//Get access_token

Route::post('oauth/access_token', function() {

   return Response::json(Authorizer::issueAccessToken());

});

  

//Create a test user, you don't need this 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())];

  });

});

Copy after login
Create BaseController.php and UsersController.php respectively with the following contents

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

//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);

    // 数组形式

    return $this->response->array($user->toArray());

  }

}

Copy after login
Then create PasswordGrantVerifier.php under app/Http/Controllers/Auth/ with the following content

##

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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;

  }

}

Copy after login
Open the oauth_client table of the database and add a client Data

1

INSERT INTO 'oauth_clients' ('id', 'secret', 'name', 'created_at', 'updated_at') VALUES ('1', '2', 'Main website', '2016–03–13 23:00:00', '0000–00–00 00:00:00');

Copy after login
Then it’s time to happily test. The APIs to be tested here are


Add a new user

http: //localhost/register

Read all user information

http://localhost/api/users

Return only the information with user id 4

http://localhost/api/users/4

Get access_token

http://localhost/oauth/access_token

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

http://localhost/api/time

Open PostMan



For more laravel framework technical articles, please visit laraveltutorial!

The above is the detailed content of Making API interface based on laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Manticore Search Development Guide: Quickly Create a Search API PHP and Manticore Search Development Guide: Quickly Create a Search API Aug 07, 2023 pm 06:05 PM

PHP and ManticoreSearch Development Guide: Quickly Create a Search API Search is one of the indispensable features in modern web applications. Whether it is an e-commerce website, social media platform or news portal, it needs to provide an efficient and accurate search function to help users find the content they are interested in. As a full-text search engine with excellent performance, ManticoreSearch provides us with a powerful tool to create excellent search APIs. This article will show you how to

How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Save API data to CSV format using Python Save API data to CSV format using Python Aug 31, 2023 pm 09:09 PM

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles