By Marone: December 2017
Spring boot rest with PUT POST HEAD OPTIONS
Goal
In my last article I built a simple hello world Rest service with spring boot, now i want to introduce more examples trying to light up various aspects of restful service.Used technologies
JDK 1.8Maven 3.2
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Model: Tutorial
package com.wstutorial.rest;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Tutorial {
private long id ;
private String name;
private String author;
public Tutorial() {
}
public Tutorial(long id , String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
..
}
Resource: TutorialResource
Set the port
server.port=10080
Rest Starter
package com.wstutorial.rest;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
public class StartRestServer {
public static void main(String[] args) {
HttpServer server;
try {
server = HttpServerFactory.create( "http://localhost:10080/api" );
server.start();
}catch (Exception e) {
System.out.println("Errormessage : " + e.getMessage());
}
}
}
Call the urls
To obtain all tutorials: http://localhost:10080/api/tutorialsJust only one specific tutorial: http://localhost:10080/api/tutorials/2
Using curl
curl -i http://localhost:10080/api/tutorials
curl -i http://localhost:10080/api/tutorials/1
curl -H "Content-Type: application/json" -X POST -d '{"author":"Adam snake","id":"1","name":"Python Basics"}' http://localhost:10080/api/tutorials
curl -H "Content-Type: application/json" -X PUT -d '{"author":"Adam changed","id":"1","name":"Python Basics"}' http://localhost:10080/api/tutorials
curl -X DELETE http://localhost:10080/api/tutorials/1
curl -X HEAD http://localhost:10080/api/tutorials/1 (doesn't work properly)
curl -X OPTIONS http://localhost:10080/api
TestClient
RestTemplate put and delete methods are void
If you want to check the response, you can use the exchange method
If you want to check the response, you can use the exchange method
@Test
public void testDeleteWithExchange() {
ResponseEntity
response = template.exchange(endpoint + "/2", HttpMethod.DELETE, null,ResponseEntity.class);
assertNotNull(response);
assertTrue(response.getStatusCode() == HttpStatus.OK);
}