Laravel's experience in developing RESTful API

I recently wrote an API with Laravel for a period of time, so let me summarize my experience.

Start

  • We can see that in API development, some websites use tokens to verify their identity, and some use OAuth2.0 . At the time, I was also struggling, and then I saw a good statement. In general, it will involve the use of OAuth for others, and the token used by yourself is enough
  • At the beginning of the design, it is best to add a version number to the route to facilitate future expansion
Route::prefix('v1')->group(function () {
	// more
});

A simple interface exampleapi instance output

verify

  • API development is always inseparable from authentication. It is recommended to use jwt-auth here . 1.0 is coming soon, and the documentation of the new version is also very clear.
  • jwt-authI was in doubt when I first used it. The token verification that comes with Laravel uses the database api_token field verification, but I don’t see the need for this .jwt-auth
    • Then I want to look at the source code myself, the resultQAQ
    • Finally went to ask the official >_<
    • The original user's information has been stored in the token encrypted
    • At the beginning, I had doubts, would it not be decrypted if stored in this way (I’m really worried about my IQ!_!)
    • Later, I remembered that jwt ran and php artisan jwt:secretgenerated the secret key at the beginning.
    • You will be safe if you don't leak it~~~

routing

  • Of course, use the official apiroute Route::apiResource(), one is stronger than five
  • The name of the route is of course the RESTful way
  • keep verb, plural, see name
  • Some long routes, what should be used to separate them?
  • Laravel uses the underline (-), because when Google includes it, it divides the keywords according to the underline. In China, it is included under the underline (_). It depends on yourself. I like the underline >_<
  • See more here: Route naming convention

form validation

You can use the form validation that comes with the controller, and it is more recommended to use the form class , which can be separated and separated, and the controller should not deal with too many things. form validationDon't be stingy with the code that can be separated~~~

data conversion

  • Laravel 's own API Resource
  • It's really convenient to use, but I found a problem, --collectionthe format is always unable to be converted, and then I gave up directly
  • single useResources
  • The use of collections is Resources::collection()found, especially easy to use>_<
  • It has to be said that when many-to-many associations are used, conditional associationsLaravel are handled too well . data conversion
  • In the above example, if the association is not loaded, the posts key will be deleted before the resource response is sent to the client.
  • This is a useful feature when there is uncertainty about whether or not to output linked data! ! !

response output

I saw this post in laravel-china at the time , and I thought this method was good, so I did the same, using the base class method to unify the response output.

abnormal

Exceptions are a lot of work, and handling them well can make your code a lot more elegant. \App\Exceptions\Handler::renderThe method can catch many useful exceptions. For example, my code is written like this: exception catch UnauthorizedHttpExceptionthis is a catch jwtexception, ValidationExceptionthis is a form exception, after catching, the form error message can be well formatted, ModelNotFoundExceptionthis is the exception that the model cannot find, After capturing, you can directly in the controller like this

// 未捕获之前的写法
public function show($id)
{
	$user = User::find($id);
	if (! $user) {
		
	}
	
	// do something
}

// 现在
public function show($id)
{
	$user = User::findOrFail($id);
}
// 甚至这样
public function show(User $user)
{
	// do something
}
  • The following two exceptions can not be caught, just to facilitate the development of the error message 404 Route not found exceptions ,NotFoundHttpException nothing to sayMethodNotAllowedHttpException

Documentation

  • Almost forgot about this, documentation is very, very important
  • I'm not a big fan of writing documentation in comments
  • use swagger-ui+swagger-edit
    • download swagger-ui
    • Only need distdirectory stuff (others can be deleted)
    • Download swagger-editor
    • Just distthe directory stuff and the root directory'sindex.html
    • I also changed it to swagger-editor, and then integrated these two things into the same directory (remember to modify the location of css and js )index.htmledit.html
    • Create two new files api.json, api.yamlprobably similar to the picture
    • api.jsonTo modify the position shown by the arrow in the figureapi
  • Access edit.htmlto writeable documents
  • Visit index.htmlto view documentation
  • After edit.htmlwriting, export json, then paste to api.jsonfileapi
  • Remember to also save the written format to api.yaml, because after clearing the cache, it will disappear the next time you visit

I wrote a package myself

  • It is convenient to create a controller and verify
  • All controllers inherit the overridden base class, and the response output is convenient.laravel-api-helper
  • For example, a full verification takes only three seconds
    • First second:php artisan api:auth
    • The second second: the picture appears to represent success;laravel-api-helper
    • The third second: The Rolex who took out his arm, make sure that only three seconds have passedarm watch
  • More usage: laravel-api-helper

The work is related to API development, and I will come back to make up after using other experience.

more references

RESTful API Design Guidelines

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325193839&siteId=291194637