Spring boot로 JWT token authentication을 이용한 API server를 만들어 보기는 했지만 귀찮은 점이 많은데, 이전에 Laravel로 간단하게 만들었던 기억이 나서 다시 Laravel로 Token Authentication을 추가한 RESTful API Server를 만들어 보고자 한다.
1. Laravel project 만들기
composer create-project --prefer-dist laravel/laravel restapi
2. mysql db 생성
3. migration, model, controller 만들기
ldw@ldw-bmax:~/laravel/restapi php artisan make:model -m -c --resource Book
4. migration
ldw@ldw-bmax:~/laravel/restapi$ php artisan migrate
5. table 구조 확인
mysql> desc books;
+------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| title | varchar(10) | NO | | NULL | |
| author | varchar(10) | NO | | NULL | |
| content | varchar(20) | NO | | NULL | |
| pages | int(11) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+------------+---------------------+------+-----+---------+----------------+
7 rows in set (0.01 sec)
6. 몇 개의 record를 직접 넣어 주었습니다.
mysql> select * from books;
+----+---------+--------+--------------------------+-------+------------+------------+
| id | title | author | content | pages | created_at | updated_at |
+----+---------+--------+--------------------------+-------+------------+------------+
| 1 | laravel | lee | laravel에 대한 기초 | 342 | NULL | NULL |
| 2 | spring | kim | spring boot 활용 | 425 | NULL | NULL |
| 3 | react | park | laravel api 와 react | 212 | NULL | NULL |
+----+---------+--------+--------------------------+-------+------------+------------+
3 rows in set (0.01 sec)
7. Rescource 생성
ldw@ldw-bmax:~/laravel/restapi$ php artisan make:resource BookResource
만들어진 BookResource 파일 수정
8. Controller에 function 추가
BookResource를 이용해 Json 을 return 가능
app/Http/Controllers/BookController
9 Route 생성
routers/api.php
10. Web page에서 다음과 같은 api로 조회 가능
localhost:8000/api/books
{
"data": [
{
"name": "laravel",
"author": "lee",
"content": "laravel에 대한 기초",
"pages": 342
},
{
"name": "spring",
"author": "kim",
"content": "spring boot 활용",
"pages": 425
},
{
"name": "react",
"author": "park",
"content": "laravel api 와 react",
"pages": 212
}
]
}
11. React project를 만들고 결과 조회
Home.js
12. 결과 test
localhost:3000으로 접속
다음은 REST 기능에 맞게 create, update, delete에 대한 기능을 추가해 본다