I’ve been writing apis with Laravel for a while now, so let’s sum up what I’ve learned.

Start

  • API development we can see that some sites use token authentication, some use OAuth2.0, AT that time I also struggled, and then saw a good statement. In general, it involves using OAuth for others, and using token for yourself is enough
  • At the beginning of the design, it is best to add a version number to the route for later expansion
Route::prefix('v1')->group(function (a) {
	// more
});
Copy the code
  • If the front end wants to cross domains, use this handy package barryvdh/laravel-cors

A simple interface example

validation

  • API development always requires validation. Jwt-auth is recommended here. 1.0 is coming, and the documentation for the new version is clear
  • Just usejwt-authSometimes I wonder,Laravelbuilt-intokenVerify that the database is usedapi_tokenField validation is missingjwt-authNeed this
    • Then want to see the source code, the resultQAQ
    • Finally went to ask the official >_<
    • The original user’s information is stored in the token and encrypted
    • Have a doubt at the beginning, such preservation, won’t be decrypted (true for their intelligence quotient worry! _!)
    • And then I remembered,jwtRun it from the startphp artisan jwt:secretThe secret key is generated
    • If you don’t say anything, you’re safe

routing

  • Of course use the officialapiThe routingRoute::apiResource()One is better than five
  • Route names are of course RESTful
  • Keep the verb plural and know the meaning by the name
  • Some long routes, what should be used to separate them?
  • Laravel uses the underscore (-), because Google included, by the underscore (_) division of keywords, domestic is by the underscore (_) included, specific to see myself, I like the underscore >_<
  • See more here: Route naming conventions

Form validation

You can use the controller’s own form validation, but it is recommended to use the form class.

Data conversion

  • Laravel API Resource
  • It’s really easy to use, but there’s one problem,--collectionThe format is always unable to turn over, and then directly gave up
  • Single useResources
  • Use of setsResources::collection()>_<
  • I have to say, in many-to-many relationships,LaravelIt was handled so wellConditions associated
  • In the example above, if the association is not loaded, the Posts key will be removed before the resource response is sent to the client.
  • This is a useful feature when there is uncertainty about whether to output associated data!!

The response output

When I saw this post in Laravel-China, I thought it was a good way, so I did the same, using the base class method for unified response output.

abnormal

Exceptions are a big deal, and handling them well can make your code a lot more elegant. The \App\Exceptions\Handler:: Render method catches many useful Exceptions. For example, my code looks like this:

UnauthorizedHttpException
jwt
ValidationException
ModelNotFoundException

// Do not capture the previous writing method
public function show($id)
{
	$user = User::find($id);
	if (! $user) {
		
	}
	
	// do something
}

/ / now,
public function show($id)
{
	$user = User::findOrFail($id);
}
// Even so
public function show(User $user)
{
	// do something
}
Copy the code
  • The following two exceptions may not be caught, just to facilitate viewing error messages during developmentNotFoundHttpException404 route not found exception, nothing more to sayMethodNotAllowedHttpExceptionThis is the method does not correspond, for example you aregetRouting,postrequest

The document

  • I almost forgot that. Documentation is very, very important
  • I don’t really like to document in comments, okay
  • useswagger-ui+swagger-edit
    • Download the swagger – UI
    • Only need todistDirectory stuff (others can be deleted)
    • Download the swagger – editor
    • As long asdistDirectory stuff and root directory stuffindex.html
    • I also put theswagger-editortheindex.htmlChanged toedit.html“, and then merge the two things into the same directory (remember to modifycss,jsThe location of the)
    • Create two new filesapi.json.api.yamlIt looks something like this
    • To modify the arrow as shown in the figureapi.jsonThe location of the
  • accessedit.htmlYou can write documents
    • Write the grammar
  • accessindex.htmlYou can view the documentation
  • inedit.htmlOnce you’ve written it, export itjsonAnd then paste toapi.jsonfile
  • Remember to also save the written format toapi.yamlBecause once the cache is clear, it will disappear the next time you access it

I wrote one myselfpackages

  • It’s easy to create controllers and verify them
  • All controllers inherit the overwritten base class for easy response output.
  • For example, complete validation takes only three seconds
    • The first seconds:php artisan api:auth
    • Second: the appearance of the graph represents success;
    • Third second: Pull out the arm of the Rolex, confirm that only three seconds have passed
  • More use: laravel-api-Helper

The job is related to API development, use other experience to come back to repair.

More reference

RESTful API design Guide