From Zero to Service — A Guide on Creating an API using Java Spring Boot

507se
507se
Feb 28 · 5 min read
Photo by Mark Tegethoff on Unsplash

In this post, we’ll go through all the steps required to get a Java Spring Boot service up and running. At a pretty high level, Spring Boot is an open-source framework that simplifies tasks such as dependency injection and assists with building APIs.

We will be implementing a service that will take care of creating, updating, and retrieving cars from an inventory. In this example, if we follow HTTP and REST standards, we can implement this using two API requests.

  1. For the request to retrieve all cars in the inventory, we will use a method of GET. Its route will be /v1/cars and it will return a list of cars.
  2. For the request to create and update cars, we will use a method of PUT. Its route will be /v1/cars/{carId}, where the {carId} parameter is the car's unique identifier. This request will have as part of its request body the full definition of the car you are going to create or update. For simplicity purposes, a car will only have a make and an id property.

We will proceed now to create our service. One of the simplest ways to achieve this task is to go to https://start.spring.io. Here you can download an empty project that will come with the right dependencies and basic scaffolding.

For purposes of this post, we will be using Maven, Java 11, and Spring Boot 2.4.3. Select these options on the page and feel free to fill out the project’s metadata with the details that are specific to your project. By the time you read this post, the Spring Boot version might have changed, feel free to pick at that point whatever the latest version is.

On the Dependencies section, select Spring Web and then click the Generate button.

Once you download this project, start by unzipping it and opening it using your favorite Java IDE. When you open the project, you’ll find a .java file named /YOUR_PROJECT_NAME/Application.java. Where, YOUR_PROJECT_NAME is the name you gave to this project. This file is the entry point that contains the main method for Spring Boot applications.

Let’s start by creating a model and a request class. Our model class will represent a car in our project. The request class will be used for HTTP requests for creating a new car.

Our model class will have one property called make of type String and a property called id of type int. Make sure to add getters, setters, equals, and hashCode methods.

For the request class, we will only be adding a property named make of type String. As you did with the model class, make sure to add getters, setters, equals, and hashCode methods.

Now that you know how a car should look like in your service, it is time to create the API. Let’s start by creating what is known as a REST Controller. REST controllers in Spring Boot have methods that map to API requests which you can call via HTTP from a client.

For you to create your first controller, you can go ahead and create a new file named CarController.java.

Controllers should be annotated with the @RestController annotation at a class level. As of now, your controller class should look like this.

The next step will be to add a method per HTTP request you are going to create. In this case, we’ll start by first creating a method for our GET request.

GET request methods should be annotated with the @GetMapping annotation. In this example, you will pass an argument of type String the name of the route, which in our example is /v1/cars.

Now you can go ahead and specificy the method return type for this request. This method should return an object of type ResponseEntity where you pass in as its generic type, your object's type. This method should have a return type ofResponseEntity<Set<Car>> as we'll be returning a set of cars.

As of now, your controller class should look like this.

For simplicity purposes, in this post, we’ll be adding and removing cars from a Set object that is in memory. Given this, our next step should be to add this object as an instance variable on your controller class.

Finally, our ‌GET method will be returning a new ResponseEntity object where you pass in as the first argument the cars object and as a second argument, the HTTP status code of OK, by using HttpStatus.OK.

The second endpoint we will be creating will be adding a car to our cars set. In this case, we'll be using the ‌PUT HTTP method. As you might have guessed, the annotation will be @PutMapping for this method.

There are a few things we need to do as part of this request.

1 — Path Variable

The path variable is part of your request’s route. In the example of the PUT request, it is the car’s id in /v1/cars/{carId}.

Path variables in Spring Boot are parameters to your requests, which are annotated with the @PathVariable annotation. In this case, you will need to add to your method a parameter of type int called carId annotated with the @PathVariable annotation.

It is important to mention that the name on the route for your parameter should match the property’s name.

2 — Request Body

The second thing you’ll do as part of this method is to add a parameter of type CreateCarRequest to this method.

Next, you’ll have to annotate this parameter with the @RequestBody annotation. This will result in your API's consumers being able to send the car information to be added as part of the HTTP request's body.

In your method, you’ll need to map the object to an object of type Car. Then, you will need to add it to your cars set.

Finally, you will need to return a ResponseEntity object with the status code of ACCEPTED using HttpStatus.ACCEPTED.

Now that we are done implementing our API, how do I make requests to my service?

It is easy, first of all, once you run the service, you need to know that it will be running, by default on port 8080.

You can either use command-line utilities such as cURL, or a UI-based application such as Postman for this.

For you to create/update cars, you will need to construct your request with the following:

Route: http://localhost:8080/v1/cars/001
Method: PUT
Request Headers: Content-Type: application/json
Request Body: { make: "My car's make" }

You should expect back getting a 202 Status Code, and the car to be added to your Set.

To verify that the car was added, let’s call the ‌GET request. This request should return the full list of all cars that have been added to the inventory.

Route: http://localhost:8080/v1/cars
Method: GET

You should expect back getting a 202 Status Code, along with a list of cars.

Hopefully, by now you’ve been able to get an idea of how to create a simple API service using Java Spring Boot. Enjoy!

Javarevisited

Medium’s largest Java publication, followed by 10000+ programmers. Follow to join our community.

By Javarevisited

Collection of best Java articles, tutorials, courses, books, and resources from Javarevisite and its authors, Java Experts and many more.  Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

507se

Written by

507se

Passionate about coding. Engineering software one keystroke at a time… ⌨️

Javarevisited

A humble place to learn Java and Programming better.

507se

Written by

507se

Passionate about coding. Engineering software one keystroke at a time… ⌨️

Javarevisited

A humble place to learn Java and Programming better.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store