How to build a REST API in 10 minutes

How to build a REST API in 10 minutes

Prerequisite : Java, any IDE

·

2 min read

Java, a stalwart in the world of programming languages, has long been the go-to choice for enterprise software development. Despite its reputation for verbosity, recent advancements in the Spring framework have revitalized the Java ecosystem, particularly with the advent of Spring Boot. In this blog, we'll embark on a journey to create a REST API using Java and Spring Boot, exploring the steps from project setup to testing the APIs.

Setting Up Your Project:

  1. Visit (https://start.spring.io/) to kickstart your project. Choose your Java version, select Maven as the build tool, and include the essential dependencies. For our REST API, we'll start with the 'spring-web' dependency.

  2. After generating the project, unzip the folder and import it into your favorite IDE. In this guide, we'll use IntelliJ IDEA for demonstration.

Creating the REST API:

  1. Navigate to src -> main -> java -> com.rest.api package and create a 'controller' package. Inside it, create a class named 'TestController.'

  2. Annotate the TestController class with @RestController and set the base mapping using @RequestMapping.

  3. Create a sample method with @GetMapping

package com.rest.api.controller;

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

@RestController
@RequestMapping("/api/v1")
public class TestController {

    @GetMapping
    public String testAPI(){
        return "Rest API is up...";
    }
}

Configuration with YAML:

  1. For configuration, create an 'application.yaml' file in src/main/resources and set the port number.

     server:
         port: 8445
    
     spring:
       application:
         name: ApiApplication
    

Testing in Browser:

  1. Run your application and use Browser to test the API by hitting the URL: http://localhost:8445/api/v1 to get this output.

  2. Create another method 'testMethod' inside the TestController class using @GetMapping, with a path variable 'msg' from the user.

     @GetMapping("/getMsg/{msg}")
         public String testMethod(@PathVariable String msg){
             return "User entered " + msg + " in the get API";
         }
    
  3. To interact with the REST API hit the URLhttp://localhost:8445/api/v1/getMsg/Enter any string here. Once you hit the URL. You should get a screen like this:

Conclusion:

Congratulations! You've successfully created a basic REST API using Java and Spring Boot. If you found this guide helpful, stay tuned for our upcoming Java and Spring Boot 101 blog series, where we'll delve deeper into advanced topics like database integration, security, testing, and deployment strategies.

Don't forget to follow and share this blog to help others on their Java and Spring Boot learning journey. If you're interested in more in-depth tutorials, stay tuned for the next installment in this series. Happy coding!