I want to make an API caller with all CRUD methods using java
I want to be able to get all the data with json then parse it and only get data with it's unique id
The thing that I can't figure out is how do I send data using an API. I get that I can use an id but what if I need to modify not one but 2 or more fields how do I do it then while Parsing a json?
So I have implemented the GET method but I can't think of how to implement the POST one
Here is the code from my methods class where I have all the methods
I'm using Jackson to parse json and Java's Httpclient
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class methods extends link{
private final ObjectMapper mapper = new ObjectMapper();
private final String url = "https://jsonplaceholder.typicode.com/todos";
public List<dataGettingBack> getAllMethod() throws IOException, InterruptedException {
HttpClient httpClientGet = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpRequest httpGetReq = HttpRequest
.newBuilder(URI.create(url))
.header("Content-Type", "application/json")
.GET()
.build();
HttpResponse<String> res = httpClientGet.send(httpGetReq, HttpResponse.BodyHandlers.ofString());
return mapper.readValue(res.body(), new TypeReference<List<dataGettingBack>>(){});
}
public List<dataGettingBack> getOne(int id) throws IOException, InterruptedException, error {
HttpClient httpGetOne = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpRequest httpOne = HttpRequest
.newBuilder(URI.create(url + "/"+ id))
.header("Content-Type","application/json")
.GET()
.build();
HttpResponse<String> responce = httpGetOne.send(httpOne, HttpResponse.BodyHandlers.ofString());
if (responce.statusCode() == 404) { throw new error("Not found "+ responce.statusCode()); }
return Collections.singletonList(mapper.readValue(responce.body(), dataGettingBack.class));
}
public void putMethod(int id) throws IOException, InterruptedException, error
{
HttpClient httpClientPut = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpRequest httpPutReq = HttpRequest
.newBuilder(URI.create(url+ "/" +id))
.PUT(HttpRequest.BodyPublishers.ofString(url))
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = httpClientPut.send(httpPutReq, HttpResponse.BodyHandlers.ofString());
}
public void postMethod() {
HttpClient httpClientPost = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpRequest httpPostReq = HttpRequest
.newBuilder(URI.create(url))
//.POST()
.header("Content-Type", "application/json")
.build();
}
public void deleteMethod(int id)
{
HttpClient httpClientDelete = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpRequest httpDelReq = HttpRequest
.newBuilder(URI.create(url))
.DELETE()
.header("Content-Type", "application/json")
.build();
}
}
Here is how I get my data back
public record dataGettingBack(Integer userId, Integer id, String title, boolean completed) {}
That's the output when I run it all
[dataGettingBack[userId=1, id=10, title=illo est ratione doloremque quia maiores aut, completed=true]]
I also have an error class
public class error extends Throwable
{ public error(String massege) { super(massege); } }
as well as link class
abstract class link
{
public String url;
}
That's what I have in main
public static void main(String[] args) throws Exception, error
{
methods methods = new methods();
List<dataGettingBack> getAll = methods.getAllMethod();
List<dataGettingBack> one = methods.getOne(10);
System.out.println(one);
}
I started my programming classes a few months ago and that's my first project on my own
I used gson library to convert the data to json when sending it
public String putMethod(int id) throws IOException, InterruptedException, error
{
HttpClient httpClientPut = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpRequest httpPutReq = HttpRequest
.newBuilder(URI.create(url+ "/" +id))
.PUT(HttpRequest.BodyPublishers.ofString(""))
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = httpClientPut.send(httpPutReq, HttpResponse.BodyHandlers.ofString());
dataGettingBack body = new dataGettingBack(3, 1,"test-test",true);
return gson.toJson(body);
}