Bom estou criando um projeto usando a API: https://opentdb.com/ e estou tendo problema na hora de trazer os dados dela para minha API, pois os dados não estão vindo fica nulo. Vou deixar meu código aqui a baixo pra se alguém poder me ajudar.
Controller:
@RestController
@RequestMapping("/quiz")
@AllArgsConstructor
public class QuizController {
private final QuizService quizService;
@PostMapping
public ResponseEntity<Void> saveQuiz(@RequestBody UrlDTO url) {
this.quizService.saveQuiz(url);
return null;
}
}
Service:
@Service
@AllArgsConstructor
@Slf4j
public class QuizServiceImpl implements QuizService {
private static final String URL = "https://opentdb.com/api.php?";
private final QuizRepository quizRepository;
private final IncorrectAnswerRepository incorrectAnswerRepository;
private final ConvertData convertData;
private final ConsumeAPI consumeAPI;
@Override
public void saveQuiz(UrlDTO url) {
try {
log.info("Buscando dados da API: {}", url);
var data = consumeAPI.consumeAPI(URL + "amount=" +url.amount() + "&category="
+ url.category() + "&difficulty=" + url.difficulty() + "&type=" + url.type());
var quizDTO = convertData.convertData(data, QuizDTO.class);
log.info("Convertendo dados para o DTO: {}", quizDTO);
var quiz = new Quiz(quizDTO.type(), quizDTO.difificulty(), quizDTO.category(), quizDTO.question(), quizDTO.correctAnswer());
List<IncorrectAnswer> incorrectAnswers = quizDTO.incorrectAnswers();
incorrectAnswers.forEach(incorrectAnswer -> {
incorrectAnswer.setQuiz(quiz);
incorrectAnswerRepository.save(incorrectAnswer);
});
log.info("Convertendo dados para a entidade: {}", quiz);
this.quizRepository.save(quiz);
log.info("Salvando quiz: {}", quiz);
} catch (Exception e) {
log.error("Ocorreu um erro ao salvar o quiz: {}", e.getMessage());
throw new QuizException("Erro ao salvar o quiz", e);
}
}
ConsumeApiImpl:
@Service
@Slf4j
public class ConsumeApiImpl implements ConsumeAPI {
@Override
public String consumeAPI(String url) {
if (url == null || url.isEmpty()) {
throw new IllegalArgumentException("URL is null or empty");
}
log.info("Iniciando chamada para a URL: {}", url);
try {
URI uri = new URI(url);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.build();
HttpResponse<String> response = client
.send(request, HttpResponse.BodyHandlers.ofString());
log.info("Resposta recebida da API: {}", response.statusCode());
return response.body();
} catch (IOException | InterruptedException | URISyntaxException e) {
log.error("Erro ao consumir a API: {}", e.getMessage());
throw new ConsumeApiException("Erro ao consumir a API", e);
}
}
}
ConvertDataImpl:
@Service
@AllArgsConstructor
public class ConvertDataImpl implements ConvertData {
private final ObjectMapper objectMapper;
@Override
public <T> T convertData(String data, Class<T> clazz) {
try {
return objectMapper.readValue(data, clazz);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
QuizDTO:
@JsonIgnoreProperties(ignoreUnknown = true)
public record QuizDTO(
@JsonAlias("type")
String type,
@JsonAlias("difficulty")
String difificulty,
@JsonAlias("category")
String category,
@JsonAlias("question")
String question,
@JsonAlias("correct_answer")
String correctAnswer,
@JsonAlias("incorrect_answers")
List<IncorrectAnswer> incorrectAnswers
) {
}