Tutorial Membuat Restful api, Implementasi validasi pada inputan, Implementasi relationship dan authorization menggunakan Lumen


1. Cara membuat restful api

  • Buat controller dengan mengetikan perintah "php artisan make:controller CustomerController --resource". Tambahan perintah "--resource" file TestController yang telah dibuat sudah langsung terisi dengan method index,show,store,edit,update,destroy untuk kebutuhan restful api.
  • Buat API Routes dengan membuka file routes->web.php. Kode nya seperti gambar dibawah ini.
  • Cek route yang sudah dibuat dengan mengetikan perintah "php artisan route:list" hasilnya bisa dilihat seperti gambar dibawah ini.



2. Cara mengimplementasikan validasi
  • Tambahkan kode ini di bootstrap/app.php
     $app->withFacades();
  • Implementasi validasi bisa dilakukan di controller dengan mengetikan kode seperti berikut.
    $validasi = Validator::make($req->all(), [
    'admin_name' => 'required|unique:admin',
    'admin_password' => 'required'
    ]);

    if ($validasi->fails()) {
    $this->data['message'] = 'Error';
    $this->data['error'] = $validasi->errors();
    return $this->data;
    }
  • Panggil validatornya dengan cara ketik kode berikut ini.
    use Illuminate\Support\Facades\Validator;
3. Implementasi Relationship

  • Sebagai contoh saya akan menggunakan dua table
    - tabel provinsi
    - tabel kota
  • Dimana Provinsi mempunyai banyak kota, dan kota hanya memiliki satu provinsi. di tabel kota ada kolom id_provinsi.
    - Buat model provinsi dan kota dengan cara ketik perintah "php artisan make:model namaModel".
  • tambahkan seperti berikut ini :
    - Model Kota
    public function kota()
    {
    return $this->hasMany(Kota::class, 'id_provinsi');
    }
  • -Model Provinsi
  • public function provinsi()
    {
    return $this->belongsTo(Provinsi::class, 'id_provinsi');
    }

Dengan ini tabel provinsi dan kota sudah saling berhubungan.
-- Selesai --

4. Cara mengimplementasikan authorization

1. Open file bootstrap/app.php, uncomment this line code :

$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);

2. Create User migration

php artisan make:migration create_users_table

3. database/migrations/[tahun]_[bulan]_[tanggal]_[randon_number]_create_users_table.php, kemdian edit function up mendjadi seperti ini: 

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('api_token', 255)->nullable();
$table->timestamps();
});

4. Run Migration

php artisan migrate

5. Create User model (usualy User model already created by default), if not just create it

php artisan make:model User

6. Open file app/User.php, and edit it


7. Create UserController

php artisan make:controller UserController

8. Open file app/Http/Controllers/UserController.php, and edit it


9. Add register route. Open file routes/web.php, and add this route

$router->post('api/users/register', 'UserController@register');

10. Let’s create post request to /api/users/register with params: name, email, password. The
return should be look like this:

{
"success": true,
"message": "Success register!",
"data": {
"name": "First User",
"email": "first_user@gmail.com",
"updated_at": "2018-12-14 04:36:03",
"created_at": "2018-12-14 04:36:03",
"id": 1
}
}

11. Great! We have implemented user registration successfully.


User Login
 
1. Create AuthController

php artisan make:controller AuthController

2. Open file app/Http/Controllers/AuthController.php, and edit it


3. Add login route. Open file routes/web.php, and add this route

$router->post('api/auth/login', 'AuthController@login');

4. Let’s create post request to /api/users/register with params: email, password. The return
should be look like this:

{
"success": true,
"api_token": "249766b5523205f7a9da9903b0eb783a5d219205",
"message": {
"id": 1,
"name": "First User",
"email": "first_user@gmail.com",
"created_at": "2018-12-14 04:36:03",
"updated_at": "2018-12-14 04:36:03"
}
}

5. Great! We have implemented user login successfully.

Authorization

1. Open file app/Http/Controllers/PostController.php, add use ouf Auth class
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class PostController extends Controller
{
…..
}


2. Open file app/Http/Controllers/PostController.php, Implement Auth Middleware in
Construct function
public function __construct(\App\Post $post)
{
$this->middleware('auth');
$this->post = $post;
}


3. Test get request with postman, http://localhost:8000/api/posts . It should return:
Unauthorized.


4. Now, try get request with api_token params,
http://localhost:8000/api/posts?api_token={YOUR API TOKEN WHEN LOGIN}. It should
return:


{
"current_page": 1,
"data": [
{
"id": 1,
"title": "Testing Update",
"status": "published",
"content": "This is Test Update",
"user_id": 1,
"created_at": "2018-12-01 05:16:47",
"updated_at": "2018-12-01 05:18:59"
}
],
"first_page_url": "http://localhost:8000/api/posts?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "http://localhost:8000/api/posts?page=1",
"next_page_url": null,
"path": "http://localhost:8000/api/posts",
"per_page": 20,
"prev_page_url": null,
"to": 1,
"total": 1
}


5. Try other Post endpoint 

Opmerkings

Gewilde plasings van hierdie blog

Tutorial REST API (Get, Post, Put, Delete) Menggunakan Postman

Game Development Life Cycle (GDLC)

PHP Request Header Menggunakan Postman