-
-
Notifications
You must be signed in to change notification settings - Fork 18
Building a Basic API Tutorial Part 2
Craig Smith edited this page Dec 19, 2019
·
9 revisions
In this section we are going to setup our first api endpoints - boilerplating them quickely, we will then later look at securing and adding additional methodology:
- install the api controller:
composer require phpsa/laravel-api-controller
- publish the config file to set your modules folder.
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
I tend to store all my Models in a model subfolder (including my user one) - you may decide to do this differently.
3 add to your routes/api.php file (at the bottom)
Route::group(['namespace' => 'Api',], function () {
});
- Lets create our first api endpoint:
php artisan make:api User
Once that is run you should find the following:
- your api.php routes file will now contain:
Route::group(['namespace' => 'Api',], function () {
Route::apiresource('users', 'UserController')->only(['index','store','destroy','show','update']);
});
- a new controller file at App\Http\Controllers\api\UserController.php
- add your routes to postman and test:
-
GET {{API_DOMAIN}}/api/users
- will show a paginated list of all the users -
GET {{API_DOMAIN}}/api/users/1
- will show a single user -
POST {{API_DOMAIN}}/api/users
- with a json body of
-
{
"name" : "test 1",
"email" : "test 2",
"password" : "test 3"
}
Will respond with 201 status and
{
"data": {
"id": 52,
"name": "test 1",
"email": "test 2",
"email_verified_at": null,
"created_at": "2019-12-19 22:47:58",
"updated_at": "2019-12-19 22:47:58"
}
}
A second call will result in an 500 error - duplicate key violation.
4. PUT {{API_DOMAIN}}/api/users/52
- with a json body of
"email" : "[email protected]",
will return 200 status and body
{
"data": {
"id": 52,
"name": "test 1",
"email": "[email protected]",
"email_verified_at": null,
"created_at": "2019-12-19 22:47:58",
"updated_at": "2019-12-19 22:50:43"
}
}
-- Optionally -- api headers middleware ? 5. Seed admin User 6. Oauth + Secrets 7. Setup in postman (optinally extra postman package to get initial api points) 8. Install api-controller package.
---- End Part 1
--- start Part 2
-
- setup Users Endpoint to map to users model
-
- add Policy for security
-
- Add Resource for response
-
- Add Request for Validation
-
- Add Scope for extra scope
- by this point should have a basic CRUD group.
- -- Custom Endpoint -- Me - for own profile
--- end Part 2
--- start part 3 (advanced extras)
- -- joins