백엔드와 로컬 python에서 구현해둔 알고리즘을 연결해야한다!!!
Spring (Controller/Service)
↓ HTTP 요청 (post_id 전달)
Python (FastAPI)
↓ 계산
Spring 으로 JSON 응답
해당 흐름대로 , fastapi를 사용하여 두 서버 간 정보를 전달하려 한다.
본격적인 개발 전에 ping 테스트를 이용하여 연결이 되는지, 설정상 문제는 없는지 확인한다.
from fastapi import FastAPI
app = FastAPI()
# request로 받아오는 정보값
class MatchReq(BaseModel):
post_id: int
@app.post("/ping")
def ping(req: MatchReq):
return {
"ok": True,
"received_post_id": req.post_id, # 해당 정보값 그대로 반환
"message": "hello from fastapi"
}
public class PingRequest {
private Long post_id;
public PingRequest() {}
public PingRequest(Long post_id) { this.post_id = post_id; }
public Long getPost_id() { return post_id; }
public void setPost_id(Long post_id) { this.post_id = post_id; }
}
받아올 객체에 대해 getter, setter 생성.
response에서도 똑같이 getter setter 생성한다.
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Service
public class PingService {
// rest template 생성
private final RestTemplate restTemplate;
public PingService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
// 해당 rest template 객체에 url과 request 객체 넣기
public PingResponse pingFastApi(Long postId) {
String url = "http://localhost:8000/ping";
PingRequest req = new PingRequest(postId);
return restTemplate.postForObject(url, req, PingResponse.class);
}
}
@RestController
public class PingController {
private final PingService pingService;
public PingController(PingService pingService) {
this.pingService = pingService;
}
@GetMapping("/test-python")
public PingResponse testPython(@RequestParam(defaultValue = "123") Long postId) {
return pingService.pingFastApi(postId);
}
}
uvicorn match_server:app --reload --port 8000
spring 생성
브라우저에서 접속
Request는 postId 단독,
Response는 result 중 user_id와 strength만 받아오도록 조정하였다.
요청은 똑같이 post_id만 받아오면 되었지만,
응답에서는 여러개의 객체를 여러개 받아와야 하기에 postMatchResDto와 그를 담는 list dto를 따로 만들었다.
package com.union.demo.dto.response;
import java.util.List;
public class PostMatchResDto {
private List<PostMatchUserDto> results;
public PostMatchResDto(){};
public List<PostMatchUserDto> getResults() {
return results;
}
public void setResults(List<PostMatchUserDto> results) {
this.results = results;
}
}
package com.union.demo.dto.response;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PostMatchUserDto {
@JsonProperty("user_id")
private Long userId;
@JsonProperty("main_strength")
private String strength;
public PostMatchUserDto() {}
public Long getUserId() {
return userId;
}
public String getStrength() {
return strength;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setStrength(String strength) {
this.strength = strength;
}
}
나머지는 괜찮앗다