はじめに

最近、Spirng Bootを勉強し始めたぞ!
APIってよく聞くけど、どうやって作るんだろう?

バックエンドエンジニアなら、APIの開発知識は
必須だよ!今回はサンプルコードを使用して
簡単なAPIを作成していくよ!
そもそもAPIって何?
API(Application Programming Interface)は、ソフトウェアアプリケーション同士が情報をやり取りするための取り決めや手順のことを指します。簡単に言えば、異なるソフトウェアやサービスがお互いにコミュニケーションをとるための窓口や規約のようなものです。
ここでの「インターフェース」は、あるものと別のものが接触する点や方法を指します。プログラミングの文脈では、APIはソフトウェア同士が情報をやり取りするための約束事や手順を提供します。
作成するサンプルAPIについて
今回は下記のtopicsテーブルのデータを取得(GET)、追加(POST)、更新(PUT)、削除(DELETE)する機能をもつAPIを作成していきます。
APIの動作確認には、無料で手軽に検証できるPostmanを使用していきます。現場でも比較的、よく使われるので、使用したことがない方は一度使用してみることをおすすめします。
id | title | content |
1 | title1 | cntent1 |
2 | title2 | cntent2 |
3 | title3 | cntent3 |
4 | title4 | cntent4 |
5 | title5 | cntent5 |
6 | title6 | cntent6 |
※DDL、DMLは以降の節で掲載しています。
作成手順概要
大まかな手順は以下の通りです。本記事は2記事に分かれており、本記事(1編)では下記、赤字部分が対象となります。
また、プロジェクトの作成やMySQL導入等の環境面については省略させていただきます。
- 環境の確認、設定ファイルの作成
- テーブルの作成、データの投入
- Modelの作成
- Controllerの作成
- Serviceの作成
- Repository(Mapper)の作成
- 動作確認
第二編は下記よりご確認ください。
開発環境
私が実施した環境は以下の通りです。
- Java11
- Gradle
- Spring Boot
- MySQL
- InteluJ CE
環境の確認、設定ファイルの作成
初めにプロジェクトに必要な依存関係を確認していきます。
私のbuild.gradleの依存関係は以下の通りです。本記事と全く同様の環境で開発したい方はmybatis、mysql、lombokあたりに留意してご自身の環境に追加してください。
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
compileOnly 'org.projectlombok:lombok'
compileOnly 'io.swagger:swagger-annotations:1.6.5'
annotationProcessor 'org.projectlombok:lombok'
runtimeOnly 'mysql:mysql-connector-java'
}
DBの接続情報(application.yml)は以下のようにしています。
spring:
dataSource:
url: jdbc:mysql://localhost/api_sample
username: test_user
password: password
sql-script-encoding: utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
テーブルの作成、データの投入
概要で紹介したtopicsテーブルのDDL、DMLを以下に掲載します。
必要に応じてご使用ください。
CREATE TABLE topics (
id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(256) NOT NULL,
content VARCHAR(256) NOT NULL
);
INSERT INTO topics(title,content) values ("title1",'content1');
INSERT INTO topics(title,content) values ("title2",'content2');
INSERT INTO topics(title,content) values ("title3",'content3');
INSERT INTO topics(title,content) values ("title4",'content4');
INSERT INTO topics(title,content) values ("title5",'content5');
INSERT INTO topics(title,content) values ("title6",'content6');
INSERT INTO topics(title,content) values ("title7",'content7');
INSERT INTO topics(title,content) values ("title8",'content8');
INSERT INTO topics(title,content) values ("title9",'content9');
INSERT INTO topics(title,content) values ("title10",'content10');
Modelの作成
Modelクラス(データベースから取得したデータをプログラムで使いやすいように管理する役割)は以下の通りです。今回はテーブルがtopicsテーブル一つなので、対応したModelを1つ作成します。
@Data
public class ApiSampleModel {
public ApiSampleModel() {
}
public ApiSampleModel(Integer id, String title, String content) {
this.id = id;
this.title = title;
this.content = content;
}
public ApiSampleModel(String title, String content) {
this.title = title;
this.content = content;
}
private Integer id;
private String title;
private String content;
}
topicsテーブルのカラムに対応するid、title、contentの変数(赤字)を含んでいます。
Controllerの作成
Controllerクラスは以下の通りです。
@RestController
@RequestMapping("/api-sample")
public class ApiSampleController {
@Autowired
ApiSampleService apiSampleService;
@GetMapping("/{id}")
public ResponseEntity<ApiSampleModel> searchTopicById(@PathVariable Integer id){
ApiSampleModel model= apiSampleService.findById(id);
return ResponseEntity.ok(model);
}
@PostMapping("/createTopic")
public ResponseEntity<ApiSampleModel> createTopic(@RequestBody ApiSampleForm form){
ApiSampleModel model = apiSampleService.addTopic(form.getTitle(),form.getContent());
return ResponseEntity.status(HttpStatus.CREATED).body(model);
}
@PutMapping("/{id}")
public ResponseEntity<ApiSampleModel> editTopic(@PathVariable Integer id,@RequestBody ApiSampleForm form){
ApiSampleModel model = apiSampleService.updateTopic(id,form.getTitle(),
form.getContent());
return ResponseEntity.ok(model);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTopic(@PathVariable Integer id){
ApiSampleModel model = apiSampleService.deleteTopic(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}
赤字の@RestControllerは対象クラスをAPIサーバー用のコントローラーして使用するためのアノテーションです。リクエストを受けて、JSONやXMLなどを返す、APIサーバーとして使用する際に付与します。
ここでは使用していませんが@ControllerはWebページ用のアプリに使用します。戻り値はHTML(View)を返します。
青字の@RequestMappingや@GetMappingはURLとコントローラーのクラス、メソッドを紐づける役割を担います。詳しくは下記の記事で解説しているので、気になる方は是非、ご確認ください。
リクエストを受け付ける際に使用するフォームクラスは下記の通りです。
@Data
public class ApiSampleForm {
private String title;
private String content;
}
終わりに
最後にSpring学習のおすすめ教材を紹介します。
多くの方に支持されている人気商品です。気になる方は是非一度、覗いてみてください。
本記事はここまでとなります。続きは第2編に記載しておりますので是非、併せて参照ください!
ご覧いただきありがとうございました。ご指摘等がございましたら頂けますと嬉しいです。
引き続き、プログラミングについて定期的に発信していきますのでよろしくお願いします!
また、もしよろしければtwitterもフォローしていただけると嬉しいです!🐢
コメント