-
-
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"
}
}
And Finally:
5. DELETE {{API_DOMAIN}}/api/users/52
will delete the record. with a response code of 204
As quick as that we have a basic api up and running, Not very secure and no validation etc... however, next we will be adding those steps in.
Some notes:
- the api.php Routes entry:
Route::apiresource('users', 'UserController')->only(['index','store','destroy','show','update']);
- you can remove endpoints from the only to lock down available entry points:
- you can add new points using standard route practices eg:
Route::get('users/fun/{id}', ...
- Model Fillable / Hidden / Casts etc do affect your responses and insertables.