This article is participating in “Java Theme Month – Java Development in Action”, see the activity link for details.

Abstract

As Java back-end development, Java objects such as Controller, Service, Dao, Mapper, XML and VO are often defined when developing API interfaces. We even use code generators to generate this code from a database! Is there any way we can skip the code and just play with the database generation API? Today I recommend a tool called magic-API to help us achieve this small goal!

SpringBoot e-commerce project mall (40K + STAR) address: github.com/macrozheng/…

Magic – API description

Magic-api is a Rapid development framework based on Java interface, writing interface will be completed through the UI interface provided by magic-API, automatically mapped to HTTP interface, without defining Controller, Service, Dao, Mapper, XML, VO and other Java objects.

use

Let’s come to wave actual combat, familiar with the use of magic-API to develop API interface.

Used in SpringBoot

Magic-api native support for SpringBoot and seamless integration with SpringBoot.

  • First of all inpom.xmladdmagic-apiCorrelation dependency;
<! -- Magic API -->
<dependency>
    <groupId>org.ssssssss</groupId>
    <artifactId>magic-api-spring-boot-starter</artifactId>
    <version>1.0.2</version>
</dependency>
Copy the code
  • In the configuration fileapplication.ymlAdd data source andmagic-apiRelated configuration;
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/magic_api? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

magic-api:
  Configure the API management page entry
  web: /magic/web
  Configure the storage mode
  resource:
    # Configure the storage location of interface resources. The options are file, database, and redis
    type: database
    # store table name
    tableName: magic_api_file
    Use the key prefix for database and redis storage
    prefix: /magic-api
    Is it read-only mode
    readonly: false
  # Enable camel name conversion
  sql-column-case: camel
  # pagination configuration
  page-config:
    Request parameter name for the page size
    size: size
    Request parameter name for page number
    page: page
    # Default page number when no page number is posted
    default-page: 1
    # Default page size when no page size is uploaded
    default-size: 10
Copy the code
  • Create a database in MySQLmagic_api, because we are configured to use the database storage interface resource, we need to create it firstmagic_api_fileTable;
CREATE TABLE `magic_api_file`
(
  `id`           bigint(255) NOT NULL AUTO_INCREMENT,
  `file_path`    varchar(255) DEFAULT NULL,
  `file_content` text,
  PRIMARY KEY (`id`)
)
Copy the code
  • To create apms_brandTable for testing;
CREATE TABLE `pms_brand` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `big_pic` varchar(255) DEFAULT NULL,
  `brand_story` varchar(255) DEFAULT NULL,
  `factory_status` bit(1) DEFAULT NULL,
  `first_letter` varchar(255) DEFAULT NULL,
  `logo` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `product_comment_count` int(11) DEFAULT NULL,
  `product_count` int(11) DEFAULT NULL,
  `show_status` bit(1) DEFAULT NULL,
  `sort` int(11) DEFAULT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
Copy the code
  • Finally start the project, accessmagic-apiUI interface, access address:http://localhost:8080/magic/web

Add and delete

Next, we will take commodity brand management as an example to experience the pleasure of using magic-API to develop interface! Use magic-API to develop API interface, just use magic-Script script in the interface.

  • First let’s write a new interface, first create a group, then create a groupnewInterface, enter the following script in the edit box;
// Use the body object to get the parameters in the request body directly
return db.table('pms_brand').insert(body);
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,POSTRequest, request path is/create, request parameters are placed inThe request body;

  • For another interface query by ID, enter the following script in the edit box;
// The path variable is retrieved from the path object
return db.table('pms_brand')
    .where()
    .eq('id',path.id)
    .selectOne();
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,GETRequest, request path is/detail/{id}, request parameters are placed inPath variable;

  • For another modified interface, enter the following script in the edit box;
return db.table('pms_brand').primary('id',body.id).update(body);
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,POSTRequest, request path is/update, request parameters are placed inThe request body;

  • To a page query query interface, enter the following script in the edit box;
return db.table('pms_brand').page();
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,GETRequest, request path is/page, request parameters are placed inRequest parametersAs already inapplication.ymlPage parameters are configured in, can be used directly);

  • Delete by ID interface, enter the following script in the edit box, delete can only use update, this design is a bit…
return db.update('delete from pms_brand where id=#{id}'); 
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,POSTRequest, request path is/delete/{id}, request parameters are placed inPath variable;

Parameter validation

Parameter validation can be done by asserting the module Assert.

  • For example, the name and initial letter of a new brand cannot be empty. Enter the following script in the edit box.
import assert;  // Import the assertion module
// If the verification fails, the operation will be terminated
assert.notEmpty(body.name,400.'Name cannot be empty! ');
assert.notEmpty(body.firstLetter,400.'The first letter cannot be empty! ');
return db.table('pms_brand').insert(body);
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,POSTRequest, request path is/test, request parameters are placed inThe request body;

  • When we don’t addnameField, the calling interface returns our own defined error message and status code.

Results transformation

We can use the Map method to transform the query data and return the data we want.

  • Let’s say we want to putshowStatusConvert to Chinese instructions and return only three required fields. Enter the following script in the edit box.
var list = db.table('pms_brand').select();
return list.map((item) = >{
    name : item.name,
    firstLetter : item.firstLetter,
    showStatus : item.showStatus? 'Do not display' : 'show'
});
Copy the code
  • Access this interface, and you can see in the execution result that the return result has been transformed.

With a transaction

Transactions are used when we use the Java development interface, and of course magic-API also supports transactions. Use the db.transaction() method, which supports both automatic and manual transactions.

  • Take modifying the brand as an example. Check whether it exists first and update it if it exists.
import assert; 
var val = db.transaction(() = >{
    var exist = db.table('pms_brand').where().eq('id',body.id).selectOne();
    assert.notNull(exist,404.'Can't find the brand! ');
    db.table('pms_brand').primary('id',body.id).update(body);
    return v2;
});
return val;
Copy the code
  • At the bottom of theInterface informationTo perform the following configuration,POSTRequest, request path is/test, request parameters are placed inThe request body;

Integrated Swagger

Write so many interfaces, are in magic- API interface for debugging. If you’re comfortable with Swagger, magic-API can also seamlessly integrate with Swagger.

  • First of all inpom.xmlTo add Swagger dependency;
<dependencies>
    <! --Swagger -- UI API -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>
Copy the code
  • In the configuration fileapplication.ymlTo add Swagger related configuration;
magic-api:
  # Integrate Swagger configuration
  swagger-config:
    # document name
    name: MagicAPI The test interface
    # Document title
    title: MagicAPI Swagger Docs
    # Document description
    description: MagicAPI Test Interface Information
    # Document version number
    version: 1.0
    # Document resource location
    location: /v2/api-docs/magic-api/swagger2.json
Copy the code
  • Visit the Swagger interface to check out ourmagic-apiAccess address:http://localhost:8080/swagger-ui.html

conclusion

Magic-api is a very interesting framework, through the use of simple scripts in the UI interface, API interface development. But as a niche framework, Magic-API still has a long way to go!

The resources

Official document: ssssssss.org/

Project source code address

Github.com/macrozheng/…

In this paper, making github.com/macrozheng/… Already included, welcome everyone Star!