reset password

REST API Using Spring Boot

In this guide we will see how to use Spring Boot to implement a REST API.

1. Create a Spring Boot Project

Go to Spring Initializr and create a project with the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: the latest stable version
  • Project Metadata: specify the Group Id and Artifact Id of your project. Under Options, select the Java version you prefer (I recommend 8) and make sure Packaging is Jar.
  • Dependencies
    • Spring Web
    • Spring Data JPA
    • MySQL Driver (or the driver for the DBMS of your choice)
    • Spring Boot DevTools (provides lots of convenience during development)

Click the Generate button to download the project, then in Eclipse, use the Import Existing Maven Project function to import it into Eclipse.

2. Configure Database Access

Unlike the myriad of configuration files in regular Spring, everything in Spring Boot uses the same configuration file src/main/resources/application.properties, and a large part of learning Spring Boot is learning the configuration properties.I recommend that you put this file in your .gitignore so you don't accidentally check this file into your source version control -- instead, version control a application.properties.sample file showing the configuration properties you use with sample values.

To connect to a database, we'll need the following properties:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Spring Boot uses Hibernate MySQL5Dialect by default. To use MySQL8Dialect instead:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

And we can use the following property to automatically create the schema in the database when the application starts:

spring.jpa.generate-ddl=true

You can check out the documentation for ways to fine control how the database is initialized.

3. REST API Example

Add the following code to the project -- note that you may need to change the package names to match your project:

Run the application, and it should automatically create the schema in the database configured in the previous step. You can insert some data into the products table, then go to the URL http://localhost:8080/products to see the list of products in JSON format.

This page has been viewed 3805 times.