Based on https://laravel-china.org/docs/dingo-api/2.0.0 documentation more concise description Dingo, direct stamp focus, focus on practice

An overview of the

Dingo API helps you build your own API easily and quickly. While this programme aims to be as flexible as possible, it still does not cover every situation and solve every problem.

The installation

Add the following code to composer. Json and perform a Composer update or Composer install

"require": {
    "dingo/api": "2.0.0-1"
}
Copy the code

Laravel

The api.php configuration file is generated in the config directory after this command is executed

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
Lumen
Copy the code

Lumen

If you are using the lumen and the Lumen does not have the vendor command, open bootstrap/app.php and register the service provider:

$app->register(Dingo\Api\Provider\LumenServiceProvider::class);
Copy the code

Facade

The API comes with two facades that you can use at your discretion.

Dingo\Api\Facade\API
Copy the code

This is the Facade of the scheduler and provides some handy helper methods.

Dingo\Api\Facade\Route
Copy the code

You can use this Facade to get the API’s current route, request, check the name of the current route, and so on.

You can register Facade in the config/app.php aliases array

'aliases' => [
	...
	'API'          => Dingo\Api\Facade\API::class,
	'ApiRoute'     => Dingo\Api\Facade\Route::class,
],
Copy the code

configuration

Configure your Dingo API in the.env file

  • API_STANDARDS_TREE
  • API_SUBTYPE
  • API_PREFIX
  • API_VERSION
  • API_NAME
  • API_CONDITIONAL_REQUEST
  • API_STRICT
  • API_DEBUG
  • API_DEFAULT_FORMAT

API_STANDARDS_TREE

Standards Tree Standard Tree

  • The unregistered tree (x) mainly represents local and private environments
  • Private trees (PRS) mainly represent projects that have no commercial distribution
  • Supplier tree (VND) mainly indicates that the published project is a conceptual thing, similar to the branch of Git, if normal development, according to x, PRS, VND description to fill in.

API_SUBTYPE

You’ll need it in the request header

API_PREFIX

Prefix of address, ‘/’ if not required

API_VERSION

The version of the interface is the default version

API_NAME

The name of the interface that is used to generate the API documentation and not used elsewhere

API_CONDITIONAL_REQUEST

Conditional requests are enabled by default, which makes it easier for the client’s caching mechanism to cache API requests when possible.

API_STRICT

Force each request to have a version, both

Accept:application/vnd.{API_SUBTYPE}.v2+json
Copy the code

API_DEBUG

Whether to enable debugging. After enabling debugging, you can access the API

API_DEFAULT_FORMAT

The type returned, usually JSON

A chestnut

API_STANDARDS_TREE=vnd
API_SUBTYPE=catering
API_PREFIX=/
API_VERSION=v1
API_NAME="My API"
API_CONDITIONAL_REQUEST=false
API_STRICT=false
API_DEBUG=true
API_DEFAULT_FORMAT=json
Copy the code

use

Here it is combined with the actual business

Table structure

member

CREATE TABLE `member` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `tel` bigint(20) DEFAULT NULL COMMENT 'Mobile phone number',
  `password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Login password',
  `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Account status 0: Normal',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `member_tel_unique` (`tel`),
  KEY `member_tel_status_index` (`tel`,`status`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Copy the code

member_data

CREATE TABLE `member_data` (
  `member_id` bigint(20) NOT NULL COMMENT 'User code',
  `sex` enum('0'.'1'.'2') COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Gender 0=> female 1=> male 2=> unknown',
  `nick_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'Name/nickname',
  `img` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'User Profile picture',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  UNIQUE KEY `member_data_member_id_unique` (`member_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Copy the code

Creating a route

$api = app ('Dingo\Api\Routing\Router');
$api->post ('user/register'.'App\Api\Controllers\UserController@register');
});
Copy the code

Create a custom response

<? php namespace App\Api; class Response { public staticfunction success($data)
		{
			return [
				'status_code'= > 200,'data'= >$data,]; } public staticfunction error($message = ' ')
		{
			return [
				'status_code'= > 0,'message'= >$message,]; } public staticfunction return($statusCode.$message.$data = [])
		{
			return [
				'status_code'= >$statusCode.'message'= >$message.'data'= >$data,]; }}Copy the code

Creating a Controller

<? php namespace App\Api\Controllers; use App\Api\DingoController; use App\Api\Response; use App\Api\Services\UserService; use Illuminate\Http\Request; class UserController extends DingoController { public$request;
		
		protected $userService;
		
		public function __construct(Request $request, UserService $userService)
		{
			$this->request = $request;
			
			$this->userService = $userService;
		}
		
		public function register()
		{
			$result = $this->userService->register ($this->request->all ());
			
			if ($result['status_code'] = = 200) {return $this->response->array (Response::return (200, 'Registration successful'['user_id'= >$result['data']])); }return $this->response->error ($result['message'], 500); }}Copy the code

Create a service

<? php namespace App\Api\Services; use App\Api\Actions\CreateUser; use App\Api\Response; use App\Models\Member; class UserService { public$member;
		
		public function __construct(Member $member)
		{
			$this->member = $member;
		}
		
		public function register($data)
		{
			try {
				return Response::success ((new CreateUser())->execute ($data));
			} catch (\Exception $e) {
				return Response::error ($e->getMessage ()); }}}Copy the code

Create action

<? php namespace App\Api\Actions; use App\Models\Member; use App\Models\MemberData; class CreateUser { /** * @param array$data
		 *
		 * @return mixed
		 * @throws \Exception
		 */
		public function execute(array $data)
		{
			
			$member           = new Member();
			$member->tel      = $data['tel'];
			$member->password = md5 ($data['password']);
			$result           = $member->save ();
			
			if (!$result) {
				throw new \Exception('Registration failed');
			}
			
			$memberData            = new MemberData();
			$memberData->member_id = $member->id;
			$memberData->sex       = "2";
			$memberData->nick_name = "";
			$memberData->img       = "";
			$memberData->save ();
			
			return $member->id; }}Copy the code

request

<? php$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://api.c.com/user/register",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"tel\"\r\n\r\n18510362698\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nzjk1221\r\n-----011000010111000001101001--",
  CURLOPT_HTTPHEADER => array(
    "accept: application/vnd.catering.v1+json"."cache-control: no-cache"."content-type: multipart/form-data; boundary=---011000010111000001101001"."postman-token: e7cf665f-3698-217a-cd71-35c3a44f42bc")));$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
Copy the code

Incurable diseases

List some common problems and solutions

How to access after version differentiation

API_VERSION specifies the default version. If you want to access other versions, add it to the header

Accept:application/vnd.{API_SUBTYPE}.v2+json
Copy the code

What if you don’t want to add a prefix

API_PREFIX=/
Copy the code

API_PREFIX cannot be empty and must be filled in, so/must be correct

Thank you

Thank you for seeing here, the above is a summary of personal research and development and code, if I can help you, I am happy. If there are any questions or mistakes in the article, please reply in the comments section to prevent me from misleading others. thank you