ipoalerts Logoipoalerts
Quick Start Examples

Java Examples

Quick start examples for integrating with the API using Java

This page provides practical quick start examples for integrating with the API using Java.

Basic Client

import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

public class IPOAlertsClient {
    private final String apiKey;
    private final String baseUrl = "https://api.ipoalerts.in";
    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;
    
    public IPOAlertsClient(String apiKey) {
        this.apiKey = apiKey;
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();
        this.objectMapper = new ObjectMapper();
    }
    
    private JsonNode makeRequest(String endpoint, String method, String body) throws IOException, InterruptedException {
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
            .uri(URI.create(baseUrl + endpoint))
            .header("x-api-key", apiKey)
            .header("Content-Type", "application/json")
            .timeout(Duration.ofSeconds(30));
        
        if ("POST".equals(method)) {
            requestBuilder.POST(HttpRequest.BodyPublishers.ofString(body));
        } else {
            requestBuilder.GET();
        }
        
        HttpRequest request = requestBuilder.build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        
        if (response.statusCode() >= 400) {
            throw new RuntimeException("HTTP error: " + response.statusCode() + " - " + response.body());
        }
        
        return objectMapper.readTree(response.body());
    }
    
    public JsonNode getIPOs(String status, String type, int page, int limit) throws IOException, InterruptedException {
        StringBuilder endpoint = new StringBuilder("/ipos?");
        if (status != null) endpoint.append("status=").append(status).append("&");
        if (type != null) endpoint.append("type=").append(type).append("&");
        endpoint.append("page=").append(page).append("&");
        endpoint.append("limit=").append(limit);
        
        return makeRequest(endpoint.toString(), "GET", null);
    }
    
    public JsonNode getIPO(String identifier) throws IOException, InterruptedException {
        return makeRequest("/ipos/" + identifier, "GET", null);
    }
}

// Usage
public class Main {
    public static void main(String[] args) {
        IPOAlertsClient client = new IPOAlertsClient("YOUR_API_KEY");
        
        try {
            JsonNode ipos = client.getIPOs("upcoming", "EQ", 1, 10);
            System.out.println("Found " + ipos.get("meta").get("count").asInt() + " upcoming equity IPOs");
            
            ipos.get("ipos").forEach(ipo -> {
                System.out.println(ipo.get("name").asText() + " (" + ipo.get("symbol").asText() + ") - " + ipo.get("priceRange").asText());
            });
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Spring Boot Integration

// IPOAlertsService.java
package com.example.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.cache.annotation.Cacheable;

import java.util.HashMap;
import java.util.Map;

@Service
public class IPOAlertsService {
    
    @Value("${ipoalerts.api.key}")
    private String apiKey;
    
    private final String baseUrl = "https://api.ipoalerts.in";
    private final RestTemplate restTemplate;
    
    public IPOAlertsService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    
    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("x-api-key", apiKey);
        headers.set("Content-Type", "application/json");
        return headers;
    }
    
    @Cacheable(value = "ipos", key = "#status + '_' + #type + '_' + #page + '_' + #limit")
    public Map<String, Object> getIPOs(String status, String type, int page, int limit) {
        Map<String, String> params = new HashMap<>();
        if (status != null) params.put("status", status);
        if (type != null) params.put("type", type);
        params.put("page", String.valueOf(page));
        params.put("limit", String.valueOf(limit));
        
        StringBuilder url = new StringBuilder(baseUrl + "/ipos?");
        params.forEach((key, value) -> url.append(key).append("=").append(value).append("&"));
        
        HttpEntity<String> entity = new HttpEntity<>(createHeaders());
        ResponseEntity<Map> response = restTemplate.exchange(
            url.toString(), HttpMethod.GET, entity, Map.class);
        
        return response.getBody();
    }
    
    @Cacheable(value = "ipo", key = "#identifier")
    public Map<String, Object> getIPO(String identifier) {
        String url = baseUrl + "/ipos/" + identifier;
        HttpEntity<String> entity = new HttpEntity<>(createHeaders());
        ResponseEntity<Map> response = restTemplate.exchange(
            url, HttpMethod.GET, entity, Map.class);
        
        return response.getBody();
    }
}

// IPOController.java
package com.example.controller;

import com.example.service.IPOAlertsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/ipos")
public class IPOController {
    
    @Autowired
    private IPOAlertsService ipoAlertsService;
    
    @GetMapping
    public Map<String, Object> getIPOs(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int limit) {
        
        return ipoAlertsService.getIPOs(status, type, page, limit);
    }
    
    @GetMapping("/{identifier}")
    public Map<String, Object> getIPO(@PathVariable String identifier) {
        return ipoAlertsService.getIPO(identifier);
    }
}

// application.yml
ipoalerts:
  api:
    key: ${IPOALERTS_API_KEY:your_api_key_here}

# Cache configuration
spring:
  cache:
    type: simple
    cache-names:
      - ipos
      - ipo

Advanced Client with Rate Limiting

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.CompletableFuture;

public class RateLimitedIPOAlertsClient extends IPOAlertsClient {
    private final BlockingQueue<RequestTask> requestQueue;
    private final ScheduledExecutorService scheduler;
    private final int requestsPerMinute;
    
    public RateLimitedIPOAlertsClient(String apiKey, int requestsPerMinute) {
        super(apiKey);
        this.requestsPerMinute = requestsPerMinute;
        this.requestQueue = new LinkedBlockingQueue<>();
        this.scheduler = Executors.newScheduledThreadPool(1);
        
        // Process requests at the specified rate
        scheduler.scheduleAtFixedRate(this::processRequest, 0, 60 / requestsPerMinute, TimeUnit.SECONDS);
    }
    
    private void processRequest() {
        try {
            RequestTask task = requestQueue.take();
            task.execute();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    public CompletableFuture<JsonNode> getIPOsAsync(String status, String type, int page, int limit) {
        CompletableFuture<JsonNode> future = new CompletableFuture<>();
        requestQueue.offer(new RequestTask(() -> {
            try {
                JsonNode result = super.getIPOs(status, type, page, limit);
                future.complete(result);
            } catch (Exception e) {
                future.completeExceptionally(e);
            }
        }));
        return future;
    }
    
    public CompletableFuture<JsonNode> getIPOAsync(String identifier) {
        CompletableFuture<JsonNode> future = new CompletableFuture<>();
        requestQueue.offer(new RequestTask(() -> {
            try {
                JsonNode result = super.getIPO(identifier);
                future.complete(result);
            } catch (Exception e) {
                future.completeExceptionally(e);
            }
        }));
        return future;
    }
    
    public void shutdown() {
        scheduler.shutdown();
    }
    
    private static class RequestTask {
        private final Runnable task;
        
        public RequestTask(Runnable task) {
            this.task = task;
        }
        
        public void execute() {
            task.run();
        }
    }
}

// Usage
public class AsyncExample {
    public static void main(String[] args) {
        RateLimitedIPOAlertsClient client = new RateLimitedIPOAlertsClient("YOUR_API_KEY", 6);
        
        try {
            // Make multiple async requests
            CompletableFuture<JsonNode> ipos1 = client.getIPOsAsync("upcoming", "EQ", 1, 10);
            CompletableFuture<JsonNode> ipos2 = client.getIPOsAsync("open", "EQ", 1, 10);
            
            // Wait for both to complete
            CompletableFuture.allOf(ipos1, ipos2).join();
            
            System.out.println("Upcoming IPOs: " + ipos1.get().get("meta").get("count").asInt());
            System.out.println("Open IPOs: " + ipos2.get().get("meta").get("count").asInt());
            
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        } finally {
            client.shutdown();
        }
    }
}