How to Create a Simple API in Java?
An API, or Application Programming Interface, is a set of protocols and tools that allow different software applications to communicate with each other. APIs allow developers to create programs that can access the functionality of other programs or services, without having to create that functionality from scratch.
Here’s an example of how to create a simple REST API in Java using the Spring Boot framework:
- Create a new Spring Boot project in your IDE.
- In the pom.xml file, add the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3. Create a new Java class called ApiController:
@RestController
public class ApiController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, world!";
}
}
4. Run the application and visit http://localhost:8080/hello in your web browser. You should see the message “Hello, world!” displayed on the page.
This is a very simple example, but it demonstrates the basic structure of a REST API in Java using the Spring Boot framework. The @RestController annotation tells Spring that this class will handle incoming HTTP requests, and the @GetMapping annotation specifies the URL that should trigger the sayHello() method.