Using Spring Boot to invoke ChatGPT/OpenAI API

OpenAI provides us the ability to invoke its features via RESTful APIs. This blog shows how to invoke the API using Spring Boot. There is nothing special here and no OpenAI Java libraries that I use. One can do the same in standard Java (non-spring) or even in more concise code with Nodejs. But here goes a sample with Spring Boot.

For starters you have to create an account with OpenAI. If this is your first time you can get free credits to use (it does expire). Otherwise you have to provide a credit card. If providing payment details then please set hard & soft billing checks (in dollar amounts). A hard check when reached will ensure that no more API calls are allowed. A soft check just sends an email notification when a limit is reached. Set it, and you will thank yourself later.

Next, you need to create an API Key to access OpenAI programmatically.

You will need the API key in a bit. The Java code is at the GitHub repo here. There are a bunch of DTOs that model the OpenAI request & response. I will skip those of course (as they are just POJO’s).

A standard Spring RestTemplate is used to invoke the REST API. Edit the application.properties to add in your API KEY

Finally run the code using