@Service
public class OpenAITranslationService {
private RestTemplate restTemplate;
public OpenAITranslationService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public OpenAIResponse translate(String language, String text) {
HttpHeaders headers = new HttpHeaders();
headers.add(OpenAIConstants.AUTHORIZATION, OpenAIConstants.TOKEN);
OpenAIRequest ai = new OpenAIRequest();
ai.setModel(OpenAIConstants.MODEL);
ai.setPrompt(OpenAIConstants.TRANSLATE + language + ": " + text);
ai.setFrequency_penalty(0);
ai.setPresence_penalty(0);
HttpEntity entity = new HttpEntity(ai, headers);
ResponseEntity<OpenAIResponse> data = restTemplate.exchange("https://api.openai.com/v1/completions", HttpMethod.POST, entity, OpenAIResponse.class);
return data.getBody();
}
}
@Value("${api.key}")
public static final String API_KEY = "";
public static final String TOKEN = "Bearer " + API_KEY;
@PostMapping("/translate")
public List<String> translate(@RequestParam String language, @RequestParam String text) {
OpenAIResponse response = service.translate(language, text);
return response.getChoicesList().stream().map(Choices::getText).collect(Collectors.toList());
}
API key is defined as api.key
in application.properties
file. I send the request but response code is 401. Where could there be a mistake?
I tried to create a new API key but the result is the same.
Most likely a copy of this: How to assign a value from application.properties to a static variable?
Here is a janky solution that I would not recommend: https://www.baeldung.com/spring-inject-static-field
Best use the accepted solution from the stackoverflow question itself. It nicely explains why its bad to inject values onto a static variable and what you can actually do.