LifeAstroAPILifeAstroAPI

Java SDK & Spring Boot

The official Java SDK covers every endpoint of LifeAstroAPI with the same method names as the Node.js, Python, PHP and Flutter SDKs. It needs Java 17 or later and works in Spring Boot 3.

  • com.lifeastroapi:lifeastroapi-java: the client. Its only dependency is Jackson (jackson-databind, which Spring Boot already ships); HTTP goes through the JDK's own java.net.http.HttpClient.
  • com.lifeastroapi:lifeastroapi-spring-boot-starter: a shared LifeAstro bean configured from application.yml.
  • Source and full README: github.com/ayanshulife/lifeastroapi-java.

Install

Maven:

<dependency>
  <groupId>com.lifeastroapi</groupId>
  <artifactId>lifeastroapi-java</artifactId>
  <version>1.3.0</version>
</dependency>

Gradle:

implementation("com.lifeastroapi:lifeastroapi-java:1.3.0")

In a Spring Boot application, add the starter instead; it brings the SDK with it:

implementation("com.lifeastroapi:lifeastroapi-spring-boot-starter:1.3.0")

First call

import com.fasterxml.jackson.databind.JsonNode;
import com.lifeastroapi.BirthInput;
import com.lifeastroapi.Lang;
import com.lifeastroapi.LifeAstro;
import com.lifeastroapi.params.ChartPlanetsParams;
import com.lifeastroapi.params.MilanAshtakootaParams;
import com.lifeastroapi.params.PanchangBasicParams;
 
LifeAstro client = LifeAstro.create(); // reads LIFEASTRO_API_KEY
 
// Today's panchang in Mumbai, in Gujarati
JsonNode day = client.panchang().basic(PanchangBasicParams.builder()
        .lat(19.076).lon(72.8777).tz("Asia/Kolkata")
        .lang(Lang.GU)
        .build());
System.out.println(day.path("tithi").path("name").asText());
 
// A Vedic birth chart
BirthInput arjun = BirthInput.of("1990-01-15", "10:30", "Asia/Kolkata", 19.076, 72.8777);
JsonNode planets = client.chart().planets(ChartPlanetsParams.builder().birth(arjun).build());
 
// Kundli matching (Ashtakoota, out of 36)
JsonNode match = client.milan().ashtakoota(MilanAshtakootaParams.builder()
        .boy(arjun)
        .girl(BirthInput.of("1992-06-20", "14:15", "Asia/Kolkata", 28.6139, 77.209))
        .build());

The client is immutable and thread-safe: build one and share it across the application. Keep the dv_live_ key on your server (an environment variable or a secrets store); never ship it in an Android or desktop app.

Parameters

Every method takes a parameter object from a builder named after the method: client.panchang().basic(...) takes PanchangBasicParams, client.western().natal().chart(...) takes WesternNatalChartParams. build() throws an IllegalStateException that lists every required value that is missing.

  • BirthInput.of(date, time, tz, lat, lon) is the chart input. It also takes LocalDate, LocalTime and ZoneId, which is handy when the birth details come from a database.
  • Place.of(lat, lon, tz) fills lat, lon and tz of panchang-style methods.
  • The SDK sends each value under the name the API reads: unprefixed date / time / tz / lat / lon for a chart, birth.* for the natal chart of transit methods, boy.* / girl.* for kundli matching, personA.* / personB.* for Western pairs.
  • Moment methods send today's date in the given time zone when date is left out.
  • lang(Lang.HI) on every Vedic method that returns names or text; Lang lists the 10 languages. Western, tarot, geo and meta methods answer in English.

Each method returns the response as a Jackson JsonNode, or as your own class:

public record Tithi(int index, String name, String paksha) {}
public record Basic(Tithi tithi, @JsonProperty("sunrise_local") String sunriseLocal) {}
 
Basic basic = client.panchang().basic(params, Basic.class);

Spring Boot

Add lifeastroapi-spring-boot-starter and set the key:

# application.yml
lifeastroapi:
  api-key: ${LIFEASTRO_API_KEY}     # from the environment, never committed
  timeout: 30s
  max-retries: 2

The starter creates one LifeAstro bean. Inject it anywhere:

@Service
public class PanchangService {
    private final LifeAstro astro;
 
    public PanchangService(LifeAstro astro) {
        this.astro = astro;
    }
 
    public JsonNode today(double lat, double lon, String tz, Lang lang) {
        return astro.panchang().basic(PanchangBasicParams.builder()
                .lat(lat).lon(lon).tz(tz)
                .date(LocalDate.now(ZoneId.of(tz)))
                .lang(lang)
                .build());
    }
}
  • The key comes from lifeastroapi.api-key, else the LIFEASTRO_API_KEY environment variable; without either the application does not start, with a message saying so.
  • The bean uses your application's Jackson ObjectMapper.
  • Define your own LifeAstro bean and the starter backs off; lifeastroapi.enabled=false turns it off. A LifeAstroBuilderCustomizer bean adds a hook or a header without replacing the bean.

Hibernate / JPA

The SDK does not touch your database. Keep the birth details in your own entity and turn them into the SDK's input:

@Entity
public class Customer {
    @Id @GeneratedValue
    private Long id;
    private LocalDate birthDate;
    private LocalTime birthTime;
    private String birthTimezone;   // "Asia/Kolkata"
    private double birthLat;
    private double birthLon;
 
    public BirthInput toBirthInput() {
        return BirthInput.of(birthDate, birthTime, ZoneId.of(birthTimezone), birthLat, birthLon);
    }
}

Cache what is shared, such as today's panchang for a city. Parameter objects have value equality, so they can be the cache key; give them an explicit date so the key changes every day:

@Cacheable("panchang")
public JsonNode panchang(PanchangBasicParams params) {
    return astro.panchang().basic(params);
}

Save a report's JSON (a @Lob column, or jsonb on PostgreSQL) if you need it again; showing it later costs no credits. The Spring Boot example in the repository does all three.

Async

client.async() has the same methods, returning CompletableFuture:

client.async().panchang().basic(params)
        .thenAccept(day -> System.out.println(day.path("tithi").path("name").asText()));

Errors, retries and credits

Every non-2xx response throws an unchecked exception with status(), code() and requestId(): BadRequestException (400), AuthenticationException (401), PaymentRequiredException (402), PermissionException (403), NotFoundException (404), RateLimitException (429, with retryAfter()), ServerException (5xx), plus LifeAstroConnectionException and LifeAstroTimeoutException. All extend LifeAstroException.

408, 425, 429, 5xx, network errors and timeouts are retried automatically (2 times by default), honouring Retry-After. Failed calls are free.

onResponse reports your credit balance, rate limit and request id after every call:

LifeAstro client = LifeAstro.builder()
        .onResponse(info -> log.info("{} credits left, request {}",
                info.creditsRemaining(), info.requestId()))
        .build();

PDF reports

The SDK turns the JSON of every client.reports() method into a branded, print-ready PDF, in the language you requested the report in. The PDF is made on your machine: LifeAstroAPI returns the report JSON (that call costs the report's credits), and rendering costs nothing.

import com.lifeastroapi.pdf.*;
 
try (ReportPdf pdf = ReportPdf.create()) {                         // keep one for the whole application
    JsonNode report = client.reports().kundliDetailed(params);     // params built with .lang(Lang.HI)
    Branding branding = Branding.builder().companyName("Acme Astro").build();
    Files.write(Path.of("kundli.pdf"), pdf.kundliDetailed(report, branding));
}
LayerClassNeeds
HTMLReportHtml.<report>(report[, branding])Nothing: a complete, self-contained document.
PDFReportPdf <report>(report[, branding]), htmlToPdf(html)Chrome, Chromium or Microsoft Edge on the machine, or a Gotenberg service. No other Java dependency.

ReportHtml and ReportPdf have one method per report, named like the client.reports() method (kundliLite, kundliDetailed, kundliBrihad, matchMaking, dashaAnalysis, numerology, sadeSati, mangalDosha, varshaphal, and horoscope for the daily, weekly and monthly horoscopes). pdf.async() has the same methods returning CompletableFuture<byte[]>. PDF engines, fonts, Docker and the Spring Boot application/pdf endpoint are covered in the README.