DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Leveraging Salesforce Using Spring Boot
  • How To Build Web Service Using Spring Boot 2.x
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Building REST API Backend Easily With Ballerina Language

Trending

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • AI-Based Threat Detection in Cloud Security
  • Performance Optimization Techniques for Snowflake on AWS
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Coding
  3. Frameworks
  4. Create and Publish Your Rest API Using Spring Boot and Heroku

Create and Publish Your Rest API Using Spring Boot and Heroku

In this tutorial, you will learn how to use Spring Boot to develop RESTful API and publish your API to Heroku.

By 
Paul Tofunmi user avatar
Paul Tofunmi
·
Apr. 04, 19 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
43.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this tutorial, you will learn how to use Spring Boot to develop RESTful API and publish your API to Heroku. First, we will build the API; upon completion, we will deploy to Heroku.


Introduction to REST

A RESTful API or web service is an application programming interface using HTTP request types: GET, POST, DELETE, and PUT to perform actions on data. It is generally preferred to its closest alternative Simple Object Access Protocol (SOAP) because it requires fewer resources. By writing APIs that adhere to RESTful practices, you are agreeing to adopt an architectural style of representing, requesting, storing data and deleting data.

GET: It is used for requesting data. You can request for a single item or list of items

PUT: It is used for updating an item.

POST: It is used for creating an item

DELETE: It is used for deleting an item.

Tools used in the tutorial

  • IDE: IntelliJ
  • Framework: Spring Boot
  • Dependency: Spring boot starter web
  • Build Tool: Maven
  • Language: Java
  • Hosting platform: Heroku

The Spring boot starter web contains everything needed to bootstrap an app such as an embedded server. Tomcat is the default.

If you don’t have a Heroku account, you may sign up using this link.

What Are We Building?

Imagine we have a bucket list of places we wish to travel to or visit in our lifetime. I hope you do. We would create an app for adding, editing, viewing and deleting items in our bucket list. In this tutorial, we will be using a non-persistent DB (ArrayList); if you want a persistent store, comment below as we have another tutorial for that.

Section 1

  1. Head over to start.spring.io and provide the group and artifact name for your app. It is a Maven project written in Java and the dependency is Web.
  2. The only dependency needed is the Web dependency.
  3. Click on generate project
  4. Extract to your computer and import the downloaded maven project to your favorite editor
  5. Open extracted folder in your editor.

Time to Write Some Code

We need to create two Java classes. One will serve as a controller for receiving request and responding with response. The second will serve as a data model.

Data Mode l(BucketList)

package com.zerotoproduction.firstrest;

public class BucketList {

    private long id;
    private String name;

    BucketList(long id, String name){
        this.id = id;
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Controller (BucketListController)

package com.zerotoproduction.firstrest;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
public class BucketListController {

    private List<BucketList> myBucketList = new ArrayList();
    private final AtomicLong counter = new AtomicLong();

    public BucketListController(){
        myBucketList.add(new BucketList(counter.incrementAndGet(), "Visit Colosseum in Rome"));
    }

    @GetMapping(value = "/")
    public ResponseEntity index() {
        return ResponseEntity.ok(myBucketList);
    }

    @GetMapping(value = "/bucket")
    public ResponseEntity getBucket(@RequestParam(value="id") Long id) {
        BucketList itemToReturn = null;
        for(BucketList bucket : myBucketList){
            if(bucket.getId() == id)
                itemToReturn = bucket;
        }

        return ResponseEntity.ok(itemToReturn);
    }

    @PostMapping(value = "/")
    public ResponseEntity addToBucketList(@RequestParam(value="name") String name) {
        myBucketList.add(new BucketList(counter.incrementAndGet(), name));
        return ResponseEntity.ok(myBucketList);
    }

    @PutMapping(value = "/")
    public ResponseEntity updateBucketList(@RequestParam(value="name") String name, @RequestParam(value="id") Long id) {
        myBucketList.forEach(bucketList ->  {
            if(bucketList.getId() == id){
                bucketList.setName(name);
            }
        });
        return ResponseEntity.ok(myBucketList);
    }

    @DeleteMapping(value = "/")
    public ResponseEntity removeBucketList(@RequestParam(value="id") Long id) {
        BucketList itemToRemove = null;
        for(BucketList bucket : myBucketList){
            if(bucket.getId() == id)
                itemToRemove = bucket;
        }

        myBucketList.remove(itemToRemove);
        return ResponseEntity.ok(myBucketList);
    }
}

As an addendum, although it is not required, you can specify a port for running your apps. If you do not specify a port, it uses port 8080 by default. I have specified my port to be 9009 in the application properties file like so:

server.port=9009

Let's Test Our APIs Locally Using Postman

  1. To get all items in bucketlist, I am using this URL:
localhost:9009

You ought to change the port number to what you have specified locally.

You should see a response similar to the one below

2. To add an item, we specify the name in the URL like so:

localhost:9009?name=Visit Big Ben

We have added “Visit Big Ben”

3. To view a single item in bucketlist:

localhost:9009/bucket?id=2

4. To edit an item, we specify the ID and new name in the URL like so:

localhost:9009?id=2&name=Visit Kensington Palace

We just changed the name of the second item in our bucket list from visit Big Ben to Visit Kensington Palace.

5. To remove an item, we specify the ID.

localhost:9009?id=2

Section 2: Deploy to Heroku

  1. You need to create an account on Heroku
  2. Install Heroku Cli. Heroku CLI is a command-line application that lets you create, deploy, and manage Heroku apps from the command line. You can download Heroku CLI from Heroku Dev Center.
  3. Login using your email and password
heroku login

4. Set up Git and create a Heroku app.

git initgit add .git commit -m "initial commit"

5. Now, create an app using Heroku create like so:

heroku create

6. Deploy the app to Heroku.

git push heroku master

7. Our app has been deployed to Heroku now.

https://intense-sands-41425.herokuapp.com/

Let’s test again, but you must remove the localhost and port with the URL given by Heroku.

For example, to get all items in our bucketlist, we use:

https://intense-sands-41425.herokuapp.com/

And to get an item, we use:

https://intense-sands-41425.herokuapp.com/bucket?id=1

That wraps up our tutorial today.

If you have any questions, you can leave a comment below.

The GitHub repository for this tutorial is here: https://github.com/zero-to-production/firstrest

Happy coding!

Spring Framework API Spring Boot app SOAP Web Protocols Web Service Data (computing) application Dependency

Opinions expressed by DZone contributors are their own.

Related

  • Leveraging Salesforce Using Spring Boot
  • How To Build Web Service Using Spring Boot 2.x
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Building REST API Backend Easily With Ballerina Language

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!