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
});
- If the front end wants to cross domains, please use this very convenient package barryvdh/laravel-cors
A simple interface example
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-auth
I 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 result
QAQ
- 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:secret
generated the secret key at the beginning. - You will be safe if you don't leak it~~~
- Then I want to look at the source code myself, the result
routing
- Of course, use the official
api
routeRoute::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. Don'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,
--collection
the format is always unable to be converted, and then I gave up directly - single use
Resources
- 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 associations
Laravel
are handled too well . - 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::render
The method can catch many useful exceptions. For example, my code is written like this: UnauthorizedHttpException
this is a catch jwt
exception, ValidationException
this is a form exception, after catching, the form error message can be well formatted, ModelNotFoundException
this 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
dist
directory stuff (others can be deleted) - Download swagger-editor
- Just
dist
the 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.html
edit.html
- Create two new files
api.json
,api.yaml
probably similar to the picture api.json
To modify the position shown by the arrow in the figure
- Access
edit.html
to writeable documents - Visit
index.html
to view documentation - After
edit.html
writing, exportjson
, then paste toapi.json
file - 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.
- For example, a full verification takes only three seconds
- First second:
php artisan api:auth
- The second second: the picture appears to represent success;
- The third second: The Rolex who took out his arm, make sure that only three seconds have passed
- First second:
- More usage: laravel-api-helper
The work is related to API development, and I will come back to make up after using other experience.