Minborg

Minborg
Minborg
Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Wednesday, March 4, 2020

Java/Spring: How to Generate an Entire Swagger Documented CRUD REST API With Speedment

As developers, one of the most cumbersome tasks we often face in our day-to-day lives is writing good and understandable documentation. It doesn’t matter if our documentation is only a few lines long explaining the core functionality of a feature or if it’s a full-blown essay demonstrating the ins and outs of a system. What matters is that the message we’re trying to convey through our documentation is precise and understandable.

In our previous article, we covered the topic of automatic REST API generation. More precisely, we demonstrated how to generate an entire CRUD REST API for your database using Speedment’s revamped Spring Integration plugin.

Today, we’ll be taking this knowledge a step further and demonstrate how to generate interactive documentation for your REST API in a single click.

If you didn’t get a chance to use the Speedment Spring plugin, we highly suggest you read our previous article as it contains the information necessary to follow this guide.

Do You Like Java Streams?

If the answer to this question is either ‘Yes!’, ‘Absolutely!’ or perhaps ‘Heck yeah!’, then Speedment is the right tool for you. Speedment is a Java ORM toolkit and runtime which uses pure Java Streams as an interface between your application and the database.

Alongside the already familiar Streams API, Speedment provides end-users with a graphical tool in order to generate a Java representation of your database in a matter of seconds, allowing them to completely stay in a Java-only environment.

If you’re interested in learning more about Speedment, head over to the documentation page where you’ll find a bunch of guides and examples. For the remainder of this article, we’ll be focusing on the new update to Speedment’s Spring plugin.

Before we Begin

In order to generate the REST API documentation, Speedment uses a combination of the OpenAPI specification and Swagger UI.

The preparation steps will differ depending on if you’re starting from scratch or not, but the end result will be the same regardless of your starting point.

If you have followed the guide in our previous article, where we explain how to generate a REST API using Speedment, you’ll only need to add a couple of dependencies to your project’s pom.xml file:
 
<dependencies>
    ...
    <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>

On the other hand, if you’re starting from scratch, head over to the Initializer where you’ll be able to generate a Speedment project with Spring support. Once you reach the Initializer, you’ll be presented with plenty of options to configure your project. One configuration option that is particularly important is the Plugins section of the Initializer.

To enable Spring support in your new Speedment project, tick the checkbox next to the "Spring" option. Once you’re happy with your project configuration, go ahead and click the Download button at the bottom of the Initializer.



When you’re ready, you can launch the Speedment Tool by executing the following command from the root folder of your project template:

mvn speedment:tool

If you’ve installed the plugin correctly, you’ll see some Spring Boot specific options which can be used to configure your REST API and documentation.

If this is your first time using Speedment, you may want to familiarize yourself with the workflow by following the “Hello Speedment” quick start guide.

Swagger Automata

For the following example, we’ll be using Sakila, a MySQL Sample Database. You can download it as a standalone instance or as a Docker container.

When you open the Speedment Tool and successfully connect to your database, you will be presented with a user interface containing the metadata information about your database and some options that you can configure:



If you click the “Generate” button found in the top banner, a Java representation of your database will get generated. To generate the documentation for your REST API, you must enable the “Generate REST documentation” option found in the project view (which is accessed by selecting the top node in the tree).

Once enabled, additional configuration options will become available allowing you to further customize your generated documentation:



The next time you regenerate your Spring project, some OpenAPI specific configurations will get generated. In order to see and use the generated documentation, you’ll need to run your Spring application. To do so, execute the following command:
 
mvn spring-boot:run


Once your Spring application is up and running, you can find your generated Swagger documentation at the following endpoint - http://localhost:8080/swagger-ui.html



Depending on how you configured your project, you might see different results in the generated documentation. For instance, if you disable REST API generation for a certain table, the next time you regenerate your project, the endpoint for that table will not be available in the documentation.

With the generated Swagger documentation, you’re able to instantly learn what REST endpoints your application has registered, what HTTP methods are available for each endpoint and execute HTTP requests for those endpoints directly from the Swagger UI:



If you’re not sure what is required in the request body, you can find the request body models at the bottom of the documentation, under the “Models” section:



Note: When connecting to the Swagger endpoint, if you get presented with the following prompt, make sure your Spring entry point is in the correct package (must be above or in the same package that the Swagger configuration is located in):



This is usually a sign that your Swagger configuration was not scanned by Spring.

Summary

Writing good and understandable documentation can be a long and tedious process. With the new update to Speedment’s Spring Boot plugin, users are able to generate interactive documentation for their REST API in a matter of seconds.

Resources

Article "How to Generate an Entire Database CRUD REST API with Speedment"
The Speedment Initializer capable of generating project templates
Speedment on GitHub

Authors

Per Minborg
Mislav Miličević

Tuesday, December 10, 2019

Java/Spring: How to Generate an Entire Database CRUD REST API with Speedment


As each year passes it is becoming nothing but obvious that the Spring Framework is one of the most widely used web development frameworks for Java. With the next decade just around the corner, Spring’s most popular module, Spring Boot, has just received a major update.

The new Spring Boot version "2.2.0" and the year "2020" are almost a perfect match. Thus, the Speedment team has now filled the gap by revamping the Spring Boot plugin.

If this is your first time hearing of Speedment, you’re in for a treat, as we will be demonstrating how the Speedment Spring Boot plugin allows developers to effortlessly build Spring database applications with Speedment, an ORM with a powerful Stream-based query API, as its backbone.

About Speedment

Speedment can be described as an ORM that the Java community deserves - a toolkit for those who like fast development and even faster applications. By leveraging the Java Stream API as its primary means of communication with your database of choice, Speedment makes developers with previous Java experience feel right at home. Alongside the easy-to-use API, Speedment provides developers with a graphical tool that generates the domain model for them in a matter of seconds.

If you’re interested in Speedment as a whole, detailed documentation with examples can be found here. The rest of this article will focus on the Spring Boot plugin.

Spring Boot: The Quickest Start 

Speedment Spring Boot plugin has been around for a while, but starting with Speedment 3.2.2 a major feature was introduced - the ability to generate an entire CRUD REST API directly from your database model.

Depending on whether you’re starting from scratch or have an existing project, the steps will differ, but rest assured that the integration process is effortless regardless of the state of your project.

If you wish to integrate Spring Boot into an existing Speedment project, you are required to add the following 2 clauses to your pom.xml:

<plugin>
    <groupId>com.speedment.enterprise</groupId>
    <artifactId>speedment-enterprise-maven-plugin</artifactId>
    <version>${speedment.version}</version>
                
    <configuration>
        <components>
            <component>com.speedment.enterprise.plugins.spring.SpringGeneratorBundle</component>
        </components>
        <appName>${project.artifactId}</appName>
        <packageName>${project.groupId}</packageName>
    </configuration>
    ... // Database connector dependency           
</plugin>
<dependencies>
 ...
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.speedment.enterprise.plugins</groupId>
    <artifactId>spring-runtime</artifactId>
    <version>${speedment.version}</version>
</dependency>
...
</dependencies>

Once added, the next time you regenerate your domain model, a Speedment-specific Spring configuration should get generated. The generated configuration handles database connection properties and bean registrations for various managers generated by Speedment.

If you’re starting from scratch, head over to the project initializer where a Spring-Boot-ready project will be generated for you. How you will configure the project is up to you, but to include the Spring Boot plugin in the generated project, make sure that the checkbox next to Spring in the Plugins section is checked. Once you’re satisfied with the project configuration, click on the Download button and you will receive a zipped-up project ready for use.


CRUD Made Easy

Once you install the plugin, some Spring Boot specific options will be available in the Speedment tool which can be used to configure your REST API. You can launch the Speedment tool by issuing the following command:
mvn speedment:tool

If this is your first time using Speedment, you may want to familiarize yourself with the workflow by following the “Hello Speedment” quick start guide.

By default, the Speedment tool won’t generate a REST API. To generate a CRUD REST API for a specific table, select the table in the tree view and check the “Generate @RestController” option along with the “REST Enable Create/Update/Delete” option. By clicking “Generate”, a set of REST mappings that implement CRUD operations for a specific table will get generated.



That’s it! No manual coding is needed. Just start the generated Spring by issuing the command:
mvn spring-boot:run

Creating Entities Using REST 

To create a new entity using your generated REST API, you must execute a POST request to the route specified in the tool. By default, the name of this route is the same as the name of your table, prefixed by the name of your schema. If you uncheck the “REST Endpoint” option, you may specify a custom route name. The request body should contain key-value pairs in a JSON object where “REST Field Name” values from the tool are keys.

If we were to have a table called ‘person’ with the columns ‘id’, ‘name’, and ‘age’, we would send the following request to create a new ‘person’ entity:

POST localhost:8080/db/person
{
    “id”: 1,
    “name”: “Jane”,
    “age”: 25
}

curl -d '{“id”: 1,“name”: “Jane”,“age”: 25}' -H "Content-Type:application/json" -X POST localhost:8080/db/person

If a column is auto-generated (or is using a sequence), you may exclude it from the POST body. If you wish to enforce the exclusion of a certain column from the POST body, click on the specific column in the tool tree view and uncheck “Include in Create Body” and regenerate your domain model. On the other hand, if you want to enforce that a certain column is present in the POST body when a request is executed, check “Required in Create Body” and regenerate your domain model.



Retrieving Entities Using REST


To retrieve our newly created entity, we must execute a GET request on the same path used for entity creation:

GET localhost:8080/db/person

curl localhost:8080/db/person/1


The executed request will return a JSON Array of all existing entities. In our case, it would return an array with just our only entity:

[
    {
        “id”: 1,
        “name”: “Jane”,
        “age”: 25
    }
]
Advanced concepts such as filters and sorters are covered in great detail in the official Speedment documentation.

Updating Existing Entities Using REST 

Updating an existing entity using your REST API is done in a similar fashion as creating an entity. Instead of a POST request, we execute a PATCH request and the route is extended by an entity identifier. What our entity identifier depends on the Primary Key column of that table. Since our PK column is a numeral type, our entity identifier will be an integer.

To update the entity we created in our previous example, we would execute the following request:

PATCH localhost:8080/db/person/1
{
    “name”: “Mike”,
    “age”: 43
}

curl -d '{“name”: “Jane”,“age”: 25}' -H "Content-Type:application/json" -X PATCH localhost:8080/db/person/1
By default, all columns are included in the PATCH body (except the Primary Key column), but they are not mandatory. If you wish to enforce the exclusion of a certain column from your request body, click on the specific column in the tool tree view and uncheck “Include in Update Body” and regenerate your domain model. On the other hand, if you want to enforce column presence in the request body, check “Required in Update Body” and regenerate your domain model.


Deleting entities using REST

Deleting an entity using your REST API is quite straightforward - we execute a DELETE request on the same path used for entity updates.

To delete the entity we’ve created and updated in the previous examples, we would execute the following request:


DELETE localhost:8080/db/person/1

curl -X DELETE localhost:8080/db/person/1

Summary

Starting new projects can sometimes be a hustle. As developers, we want to avoid these inconveniences as much as possible and dive straight into coding. With Speedment's new Spring Boot plugin, developers can get ahead of the game by automatically generating all necessary configurations and REST controllers directly from the database.

We hope you’ve enjoyed this brief guide to the new CRUD features the Speedment Spring Boot plugin provides. If you’re interested in a more detailed explanation of the new features, head over to the official documentation where you will find in-depth explanations and examples of the new CRUD features.

Authors

Per Minborg
Mislav Miličević