创建简单的 REST API 以进行实践自动化测试
API 是应用程序编程接口的首字母缩写,它是一种允许两个应用程序(服务)相互通信的软件中介。
想象一下它就像餐厅里的服务员。它会帮你获取订单信息,并将其传递给厨房里的厨师。当食物做好后,它会去取食物并送到你面前。
用技术术语来说,数据库就像厨房。API 就像服务员。而你(客户)就像客户的请求。
我们可以通过多种方式/语言来创建 API。但在本教程中,我将向您展示如何使用 Java Spring/Tomcat 和 mvn 来实现。
我们交互的数据库将是 MySQL。
1.安装MySQL并创建新数据库:
MySQL 是一个开源的关系型数据库 (RDMBS),您可以放心安装和使用。
由于我使用的是 Ubuntu,因此安装指南可以参考MySQL 安装
之后,您可以创建自己的数据库,在此博客文章中,将其命名为 gamelistapi。
请参阅此文以了解如何在 MySQL 中创建数据库创建数据库。
为了使用数据库,我经常使用 DataGrip(Jetbrains 开发的一款开发工具)。DataGrip 支持很多数据库:MySQL、Oracle、SQL Server、Postgres、MariaDB 等等。
Datagrip 官方网站在 [这里][ https://www.jetbrains.com/datagrip/ ]
创建新数据库后,您可以打开 Datagrip 通过 SQL 查询或 Datagrip GUI 与数据库进行交互。
与游戏列表 API 连接的配置:
2.设置Java和Maven环境:
您将需要安装 Java(我目前正在使用 Java 11,但您可以使用 Java 8,因为它是稳定版本)。
前往 Oracle 网站下载适合您系统的 Java 安装程序:Java Oracle
之后安装 Maven 工具(用于构建 Java 应用程序)。请前往 Maven 下载官方网站下载 Maven:Maven 最新版本
在项目中使用 Java 和 Maven 之前,您需要先设置 Java 和 Maven 的全局环境。(具体设置取决于您使用的操作系统)
3.项目结构:
-
在 maven 项目中,我们将有一个 pom 文件:用于存储我们将用于项目的依赖项(库)
-
在 src/resources 文件夹中,我们通常会放置项目使用的数据库、环境、配置信息等。在本项目中,我们放置的是 db.properties 文件。
文件 db.properties 如下所示:
// MySQL properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/gamelistapi?useSSL=false
mysql.user=****
mysql.password=*****
// Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
// C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
```
mysql.driver is the param we would use for jdbc driver for MySQL.
mysql.url is the url for our local database. (Usually MySQL will take the port 3306)
mysql.user and mysq.password you will put your user and password of your created database in there.
- In src/main packages, you will have source code that implement the gamelist api.
I will cover about structure of Spring framework in another blog post.
- Features of gamelist api will have: create new game, update game, get game data, and delete the game.
4.Build gamelist api with maven:
Usually to run project from maven, you will run with 'mvn ...'
Since our project use tomcat7, the command line will be:
mvn tomcat7:run
5.Using gamelist api with postman:
Postman is a free tool for users interact with API.
You can download postman from this link: [postman](https://www.getpostman.com/downloads/)
For example, if you want to get all the games from the API, the screenshot looks like this.

If you want to create new game:

Feel free to get the code from my github [gamelist-api](https://github.com/cuongld2/gameListApi)
Next blog post, I will show you about how to test these APIs with Serenity.
Thank you all for reading! :-*
Notes: If you feel this blog help you and want to show the appreciation, feel free to drop by :
[<img src="https://thepracticaldev.s3.amazonaws.com/i/cno42wb8aik6o9ek1f89.png">](https://www.buymeacoffee.com/dOaeSPv
)
This will help me to contributing more valued contents.