Build A Simple REST API With Spring

Build A Simple REST API With Spring

To get our project up and running, we use Spring Initializr.

Initializr generates spring boot project with just what you need to start quickly.

https://start.spring.io/

No alt text provided for this image

We can leave the settings for the project, Language and Spring Boot version as the default.

We search for dependencies to add and select the Spring Web dependency. That is the only dependency we need for this task.

The generate button on the bottom left is then clicked to download the project.

You open the project with your IDE (I use IntelliJIDEA) and allow the dependencies to be downloaded.

The starter code with the main method would resemble that below:

@SpringBootApplication
public class SpringrestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringrestApplication.class, args);
    }

}

Run the application, open your browser and navigate to localhost:8080 (it runs on port 8080 by default)

You might encounter an error page, don't panic:

No alt text provided for this image

Spring uses a default Whitelabel error page in case of a server error. Currently, there is not code logic to handle the "localhost:8080/" request.

We would create a Controller class to handle the "/" root path. Make sure to annotate the class with the @RestController annotation.

@RestController
public class Controller {

    @GetMapping("/")
    public String home() {
        return "Hello";
    }

    @GetMapping("/{name}")
    public String hello(@PathVariable String name) {
        return "Hello " + name;
    }

}


Let's navigate to localhost:8080 again

No alt text provided for this image

The @GetMapping("/{name}") allows for Path Variables, so let's say we navigate to http://localhost:8080/Lemuel

We get:

No alt text provided for this image

We have just brushed through the basics.

You can watch the 10 minutes in-depth tutorial below about building REST API's with Spring. In the Tutorial below you would be shown other functions you can perform in Spring and access to download the source code.



Lemuel, thanks for sharing!

Like
Reply

To view or add a comment, sign in

More articles by Lemuel Ogbunude

  • Kotlin Sequences vs Kotlin Collection Functions

    When we need to run a couple of operations on a Kotlin collection, it's good to know the difference between using the…

    1 Comment
  • Java is still free!

    I see a lot of posts lamenting about how Java is now being paid for. I feel a lot of people are getting it wrong…and…

Others also viewed

Explore content categories