백엔드 개발 끄적끄적 02

kiwi_jelly·2026년 2월 17일

졸프

목록 보기
2/4

백엔드와 로컬 python에서 구현해둔 알고리즘을 연결해야한다!!!

1) Ping 코드로 간단 연결 테스트

Spring (Controller/Service)
        ↓  HTTP 요청 (post_id 전달)
Python (FastAPI)
        ↓  계산
Spring 으로 JSON 응답

해당 흐름대로 , fastapi를 사용하여 두 서버 간 정보를 전달하려 한다.

본격적인 개발 전에 ping 테스트를 이용하여 연결이 되는지, 설정상 문제는 없는지 확인한다.

1. match_server.py

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"
    }

2. 요청/응답 DTO

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 생성한다.

3. Config : BEAN 생성

@Configuration
public class AppConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

4. Service : FastAPI 호출

@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);
    }
}

5. Controller : 브라우저에서 확인

@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);
    }
}

6. 실행

  1. python에서 실행
uvicorn match_server:app --reload --port 8000
  1. spring 생성

  2. 브라우저에서 접속

2) 실전...

1. match_server.py

Request는 postId 단독,
Response는 result 중 user_id와 strength만 받아오도록 조정하였다.

2. 요청/응답 DTO

요청은 똑같이 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;
    }
}

나머지는 괜찮앗다

profile
In lapidem

0개의 댓글