Home > OS >  How to call an API endpoint during runtime?
How to call an API endpoint during runtime?

Time:03-14

how can I call an API endpoint at runtime? I'm new to this business I have an endpoint in my spring project that saves products (a json file that is in the project) to MongoDB I need products to be saved before the user uses my application

CodePudding user response:

You need a client to make the request at the appropriate time. There are lots of options, so i will list only a few:

  1. Java provided functionality. Not really recommended, unless you want to learn the basics. You can read here.
  2. Apache HttpComponents. A simple get request example:
ObjectMapper mapper = new ObjectMapper();
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet("https://your.host/endpoint");
HttpResponse httpResponse = client.execute(get);
YourClass response = mapper.readValue(httpResponse.getEntity().getContent(), YourClass.class);
  1. Spring WebClient. There are more guides, just google them if you need. Simple get request example:
WebClient webClient = WebClient.builder().build();
YourClass conversionResponse = webClient.get()
        .uri("https://your.host/endpoint")
        .retrieve()
        .bodyToMono(YourClass.class)
        .block(Duration.ofSeconds(10));

Naturally there are more tools. Play around with them, and pick what's best for your specific need.

  • Related