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 use
jwt-auth
Sometimes I wonder,Laravelbuilt-intokenVerify that the database is usedapi_tokenField validation is missingjwt-auth
Need this- Then want to see the source code, the result
QAQ
- 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 start
php artisan jwt:secret
The secret key is generated - If you don’t say anything, you’re safe
- Then want to see the source code, the result
routing
- Of course use the official
api
The 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,
--collection
The format is always unable to turn over, and then directly gave up - Single use
Resources
- Use of sets
Resources::collection()
>_< - I have to say, in many-to-many relationships,
Laravel
It 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 development
NotFoundHttpException
404 route not found exception, nothing more to sayMethodNotAllowedHttpException
This 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
- use
swagger-ui
+swagger-edit
- Download the swagger – UI
- Only need to
dist
Directory stuff (others can be deleted) - Download the swagger – editor
- As long as
dist
Directory stuff and root directory stuffindex.html
- I also put the
swagger-editor
theindex.html
Changed toedit.html
“, and then merge the two things into the same directory (remember to modifycss,jsThe location of the) - Create two new files
api.json
.api.yaml
It looks something like this - To modify the arrow as shown in the figure
api.json
The location of the
- access
edit.html
You can write documents- Write the grammar
- access
index.html
You can view the documentation - in
edit.html
Once you’ve written it, export itjson
And then paste toapi.json
file
- Remember to also save the written format to
api.yaml
Because 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
- The first seconds:
- 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