Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
第7回 社内勉強会 「REST APIを作ってみよう」
Search
Wemotion, Inc
December 24, 2022
Programming
160
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
第7回 社内勉強会 「REST APIを作ってみよう」
Wemotion, Inc
December 24, 2022
More Decks by Wemotion, Inc
See All by Wemotion, Inc
第10回 社内勉強会「GPT x Embeddingで質疑応答を試す」
wemotion
0
93
第9回 社内勉強会「ChatGPTを使い倒そう」
wemotion
0
250
第8回 社内勉強会 「サーバーを構築してWebページを公開してみよう」
wemotion
0
170
第5回 社内勉強会 「設計 後編」
wemotion
0
110
第4回 社内勉強会 「設計 前編」
wemotion
0
160
第3回 社内勉強会 「要件定義 後編」
wemotion
1
180
第2回 社内勉強会 「要件定義 前編」
wemotion
1
340
第1回 社内勉強会 「セキュアプログラミング」
wemotion
0
270
Other Decks in Programming
See All in Programming
Event is what happens
moro
2
1.7k
現場と育てるRailsモデリング 〜Spreadsheetから始めたモデル設計〜
siroemk
2
1.1k
AI時代のIaC入門 〜なぜインフラをコードで管理したいのか?〜 / Introduction to IaC in the AI Era
akihisaikeda
5
1.1k
React Native에 현대적인 빌드 도구 더하기: Rollipop 구현기
leegeunhyeok
0
150
Inertia Rails: The One-Person Framework with React & Friends
skryukov
0
170
Unity6 URPによる海底をテーマにしたVJシステムの解説 | Unity Shader 完全に理解した 勉強会
gam0022
0
390
3回つくってわかった、 定期実行ジョブ基盤の本質情報
takai
4
3.3k
Spec-Driven Development - Why Vaadin Is the Perfect Fit
simas
PRO
0
150
気持ちぃ〜角丸 Squircle
ryu1013
0
360
コードで差別化できない時代の ソフトウェアエンジニアリング / Software Engineering in an Era Where Code Doesn’t Differentiate
kishida
2
200
複雑なUIコンポーネントとの ⻑い付き合い⽅:波及するバグからテスト戦略を経て、安全な再設計へ
mixplace
0
480
Modernizing iOS Apps
seyfoyun
0
120
Featured
See All Featured
Building Better People: How to give real-time feedback that sticks.
wjessup
371
20k
Visualization
eitanlees
153
17k
Facilitating Awesome Meetings
lara
57
7.2k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
3.1k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.9k
Designing for Timeless Needs
cassininazir
1
530
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
56
3.5k
Docker and Python
trallard
47
4.2k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
1
3.5k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
508
140k
Agile Actions for Facilitating Distributed Teams - ADO2019
mkilby
0
320
WCS-LA-2024
lcolladotor
0
930
Transcript
REST APIを作ってみよう 第7回 社内勉強会 2022/12/24
準備
Docker環境を構築し、 dockerとdocker-composeコマンドを使用できるようにする Windows編 https://media.wemotion.co.jp/technology/docker-windows/ Mac編 https://media.wemotion.co.jp/technology/docker-mac/ Docker環境構築
PostmanはGUI上からHTTPリクエストを自由度高く発行することができる PostmanをChrome Extensionsからインストール https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=ja Postmanインストール ※ 初回実行時にGoogleアカウンなどで無料登録(簡単な質問回答)とSign Inが必要
PHPの代表的なフレームワーク MVCモデルを採用している M: Model V: View C: Controller LaravelでREST
APIを開発 出典: https://laravel.com/
gitコマンドが使用可能な場合は git clone gitコマンドを使用しない場合は「Download ZIP」して解凍 https://github.com/wemotion-inc/docker-laravel-api 第7回 勉強会用 リポジトリ
ソースコードの準備 git clone or Download ZIP にてソースコードを取得
ダウンロードしたディレクトリに入り、コンテナの初回起動を行う PHP環境、DB(MySQL)環境、Webサーバー(Nginx)環境を、 一発でコンテナ上に構築できるよう設定済み コンテナ準備 # docker-composeでコンテナ起動(初回は必要なリソースをインストール)
docker-compose up -d --build
REST API
REST APIのRESTとは、「Representational State Transfer」の略 代表的な特徴 - 統一されたインターフェイス - ステートレス
- 階層型システム - キャッシュ可能性 - オンデマンドのコード REST APIとは 出典: https://aws.amazon.com/jp/what-is/restful-api/
URIによってリクエストを行うリソースを特定し、 HTTPメソッドを使用することでサーバーサイド(DB)に対して - データ取得 - データ登録 - データ更新 - データ削除
などをHTTPリクエストすることができる 一般的にJSON形式でデータのやりとりを行う REST API概要
HTTPメソッドと用途 メソッド 用途 GET 指定されたURLにあるリソースを 参照する(Read) リクエスト パラメータでフィルター処理をサーバーに指示可能 POST
サーバーにデータを送信し 作成する(Create) PUT サーバー上の既存のリソースを 更新する(Update) DELETE サーバー上のリソースを 削除する(Delete)
REST API I/F設計
要件 本の情報登録、本の一覧取得、本の情報更新、本の削除が可能なAPI 仕様 - 登録情報 - タイトル、著者、出版年 - 絞り込みで一覧取得
- 出版年で絞り込み “本”についてCRUDするREST API
URI設計 URI メソッド 概要 /api/books GET 本の一覧を取得 クエリパラメータ 出版年(published_yaer) で絞り込み
/api/books POST 本の情報を登録 /api/books/{book_id} GET book_idにマッチする本の情報を 取得 /api/books/{book_id} PUT book_idにマッチする本の情報を 更新 /api/books/{book_id} DELETE book_idにマッチする本を 削除
ハンズオン
Docker コンテナ上のPHP環境にLaravelをインストールする Laravelインストール # PHP環境(app)のコンテナに入る docker-compose exec app bash #
Laravelをインストール composer create-project --prefer-dist "laravel/laravel=8.*" . # コンテナからの抜け方 exit
/src/.env ファイルの DB_CONNECTION の部分を以下に差し替え
※ 11~16行目あたり DB接続の設定ファイル作成 DB_CONNECTION=mysql DB_HOST=db DB_PORT=3306 DB_DATABASE=database DB_USERNAME=root DB_PASSWORD=password
Laravelのアプリケーションで利用したいテーブルの作成などを行う ※ 直接SQLを書かなくてもPHPの記述からテーブル作成を行うことができる マイグレーション
# PHP環境(app)のコンテナに入る(既に入ってる場合は Migrateへ) docker-compose exec app bash # Migrateを行う php artisan migrate
マイグレーションで作成されたテーブル一覧を見てみる テーブルの確認 # DB環境(MySQL)のコンテナに入る docker-compose exec db bash # MySQLに入る
mysql -u root --password=password # データベース領域指定 use database; # テーブル一覧表示 show tables;
Bookモデルクラス作成 # PHP環境(app)のコンテナ内で実行 php artisan make:model Book --migration
src/app/Models/Book.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Book
extends Model { use HasFactory; protected $fillable = [ 'title', 'author', 'published_year' ]; }
src/database/migrations/xxxx_create_books_table.php public function up() { Schema::create('books', function (Blueprint $table) {
$table->id(); $table->string('title'); $table->string('author'); $table->integer('published_year'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down()
migrate & Bookコントローラー作成 # PHP環境(app)のコンテナ内で実行 php artisan migrate # コントローラー作成
php artisan make:controller BookController --api
routes/api.php <?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\BookController; Route::middleware('auth:sanctum')->get('/user', function
(Request $request) { return $request->user(); }); Route::apiResource('/books', BookController::class);
ルーティング確認 # PHP環境(app)のコンテナ内で実行 php artisan route:list
コントローラー メソッド追加(POST) app/Http/Controllers/BookController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Book;
class BookController extends Controller { /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $book = Book::create($request->all()); return response()->json( $book, 201 ); }
コントローラー メソッド追加(GET) <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Book; class
BookController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $books = Book::all(); return response()->json( $books, 200 ); }
PostmanからPOST(データ登録)してみる 「POST」を選択 URL: http://localhost:8081/api/books Bodyに「JSON (application/json)」形式で title, author, published_yearを設定
Sendを実行して Statusが201 Createdなら登録成功!
PostmanからGET(データ取得)してみる 「GET」を選択 URL: http://localhost:8081/api/books Sendを実行して Statusが200 OKで 登録したJSONが返って来れば成功!
コントローラー メソッド追加(GET 1件) /** * Display the specified resource. *
* @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $book = Book::where('id', $id)->get(); if ($book) { return response()->json( $book, 200 ); } else { return response()->json( [ 'message' => "Book $id not found" ], 404 ); } }
PostmanからGET(book_idで取得)してみる 「GET」を選択 book_id=4を取得したい場合 URL: http://localhost:8081/api/books/4 Sendを実行して Statusが200 OKで指定のbook_idを持つ JSONが返って来れば成功!
コントローラー メソッド追加(UPDATE) /** * Update the specified resource in storage.
* * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $update = [ 'title' => $request->title, 'author' => $request->author, 'published_year' => $request->published_year ]; $book = Book::where('id', $id)->update($update); if ($book) { return response()->json( $book, 201 ); } else { return response()->json([ 'message' => 'Book not found', ], 404); } }
PostmanからUPDATE(データ更新)してみる 「PUT」を選択 book_id=4をデータ更新したい場合 URL: http://localhost:8081/api/books/4 Bodyに「JSON (application/json)」形式で 更新後のtitle, author, published_yearを設定
Sendを実行して Statusが201 Createdで更新成功!
コントローラー メソッド追加(DELETE) /** * Remove the specified resource from storage.
* * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $book = Book::where('id', $id)->delete(); if ($book) { return response()->json([ 'message' => 'Book deleted successfully', ], 202); } else { return response()->json([ 'message' => 'Book not found', ], 404); } }
PostmanからDELETE(データ削除)してみる 「DELETE」を選択 book_id=5をデータ更新したい場合 URL: http://localhost:8081/api/books/5 Sendを実行して Statusが202 Acceptedで削除成功!
コントローラー メソッド追加(GET 絞り込み) /** * Display a listing of the
resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $published_year = $request->query('published_year'); if ($published_year) { $books = Book::where('published_year', $published_year)->get(); } else { $books = Book::all(); } return response()->json( $books, 200 ); }
PostmanからGET(絞り込み)してみる 「GET」を選択 published_year=2022のデータを取得したい場合 URL: http://localhost:8081/api/books?published_year=2022 Sendを実行して Statusが200
OKで成功!
app\Http\Controllers\BookController.php https://github.com/wemotion-inc/docker-laravel-api/wiki/app%5CHttp%5CControllers%5 CBookController.php
None