[python] Open API를 통한 축산물 이력제 이력번호 발급 및 거래신고





💡 축산물 이력제 API에 파이썬 스크립트를 이용해서 이력번호를 전송

💡  이력번호 발급(data1), 선별포장 신고(data2), 거래 신고(data3) 3단계 처리

💡 자료 전송 후에는 구글 이메일로 알림 메일을 발송




1. 오픈API key 발급방법

  • https://pub.mtrace.go.kr/ 축산물 이력제 사이트 로그인
  • 정보수정 > 개인정보 변경 > 하단 OpenAPI Key 발급 선택







2. 서비스별 serviceKey 확인




3-1. 이력번호 발급(data1)

  • userId, apiKey 는 인증을 위해 필요한 정보이고 serviceKey 는 사용하는 API를 구분하는 값입니다.
  • item 내 transParam이 실제 전송하고자 하는 데이터입니다.
  • 위 첨부된 가이드의 내용에 따라 파리미터의 값을 생성합니다.

    1
    2
    3
    4
    5
    data1 = {"userId""000000",
            "apiKey""00000000000000000000",
            "serviceKey""addEggHistNo",
            "item": [{"transParam":trace_num+"|0000000000|00000000000|"+report_date+"|0000000000|00000000000|사업자명|대표자명|전화번호|핸드폰번호|주소|N|N|N|N|N|202239|OY2BC|사업자명|대표자명|N|N|N|N|N|N|314001|"+report_date+"||315002|||0|0|0|300|0|0|"}]
            }


    cs

  • 데이터를 json형태로 변환 후 utf8로 인코딩해 줍니다.

    1
    2
    3
    4
    5
    data_EggHistNo = json.dumps(data1).encode('utf8')
    resp1 = requests.post(url, headers=headers, data=data_EggHistNo)
     
    print(resp1.status_code)
    print(resp1.text)
    cs





3-2. 선별포장 신고(data2)

  • 위 가이드의 내용에 따라 파리미터의 값을 생성합니다.

    1
    2
    3
    4
    5
    data2 = {"userId""000000",
            "apiKey""00000000000000000000",
            "serviceKey""addEggPackng",
            "item": [{"transParam":"0000000000|00000000000|"+trace_num+"|"+report_date+"|"+report_date+"|260012|0000000000|00000000000|사업자명|대표자명|전화번호|핸드폰번호|주소|N|N|N|N|N|202239|고유번호|사업자명|대표자명|N|N|N|N|N|N|314001|"+report_date+"||0|0|0|300|0|0||315002|||0|0|0|290|0|0|||"}]
            }
    cs
  • 데이터를 json형태로 변환 후 utf8로 인코딩해 줍니다.

    1
    2
    3
    4
    5
    data_EggPackng = json.dumps(data2).encode('utf8')
    resp2 = requests.post(url, headers=headers, data=data_EggPackng)
     
    print(resp2.status_code)
    print(resp2.text)
    cs






3-3. 거래 신고(data3) 

  • 위 가이드의 내용에 따라 파리미터의 값을 생성합니다.
  • 데이터 생성시 3번째 파라미터인 신고인 농장식별번호는 반드시 제외합니다. 포함시 전송은 성공하나 시스템에서 자료 조회가 불가합니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    data3 = {"userId""000000",
            "apiKey""00000000000000000000",
            "serviceKey""addEggTrade",
            "item": [
                            {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|120|0|0||N||||"},
                            {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|120|0|0||N||||"},
                            {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|30|0|0||N||||"},
                            {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|20|0|0||N||||"}
                    ]
            }
    cs
  • 데이터를 json형태로 변환 후 utf8로 인코딩해 줍니다.

    1
    2
    3
    4
    5
    6
    7
    data_EggTrade = json.dumps(data3).encode('utf8')
    resp3 = requests.post(url, headers=headers, data=data_EggTrade)
     
    print(resp3.status_code)
    print(resp3.text)
     
     
    cs



[참고] 구글 이메일 발송

  • 구글 SMTP 서비스를 이용해서 메일을 발송합니다.
  • 자세한 구글 메일 발송 관련 포스트는  이곳을 읽어주세요
  • json.loads(resp1.text) 을 통해 1,2,3단계의 데이터를 불러와 필요한 자료를 추출하도록 파싱합니다.
  • 3단계 데이터의 경우 오류가 발생하면 수신 되는 자료 형태가 string 이고, 성공하는 경우 리스트 형이기에 수신 메시지에 따라 처리 방법을 분기해 줍니다.
  • 파싱된 데이터는 html 형태로 작성하고 메일 본문과 제목을 만듭니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    # 세션 생성
    = smtplib.SMTP('smtp.gmail.com'587)
     
    # TLS 보안 시작
    s.starttls()
     
    # 로그인 인증
    s.login('구글이메일''비밀번호키')
     
    # create MIMEBase
    send_time = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
    message = MIMEMultipart("alternative")
    message["Subject"= send_time+' eggTrace.py가 실행되었습니다.'
     
    # Create the plain-text and HTML version of your message
    #addEggHistNo
    json_data1 = json.loads(resp1.text)
    json_header1 = json_data1["header"]
    json_str_1_1 = json_header1["resultCode"]
    json_str_1_2 = json_header1["resultMsg"]
     
    json_body1 = json_data1["body"]
    json_str_1_3 = json_body1["items"]
    json_str_1_4 = json_str_1_3["item"]
    json_str_1_5 = json_str_1_4["serviceKey"]
    json_str_1_6 = json_str_1_4["transParm"]
     
    resp1_body = '이력번호 : ' + trace_num + '<br>신고일자 : ' +report_date + '<br><br>resultCode : ' + json_str_1_1
    resp1_body = resp1_body +'<br> resultMsg : ' + json_str_1_2 + '<br> serviceKey : ' +json_str_1_5 +'<br> transParm : <br>' +json_str_1_6
     
    #addEggPackng
    json_data2 = json.loads(resp2.text)
    json_header2 = json_data2["header"]
    json_str_2_1 = json_header2["resultCode"]
    json_str_2_2 = json_header2["resultMsg"]
     
    json_body2 = json_data2["body"]
    json_str_2_3 = json_body2["items"]
    json_str_2_4 = json_str_2_3["item"]
    json_str_2_5 = json_str_2_4["serviceKey"]
    json_str_2_6 = json_str_2_4["transParm"]
     
    resp2_body = 'resultCode : ' + json_str_2_1
    resp2_body = resp2_body +'<br> resultMsg : ' + json_str_2_2 + '<br> serviceKey : ' +json_str_2_5 +'<br> transParm : <br>' +json_str_2_6
     
    #addEggTrade
    json_data3 = json.loads(resp3.text)
    json_header3 = json_data3["header"]
    json_str_3_1 = json_header3["resultCode"]
    json_str_3_2 = json_header3["resultMsg"]
     
    json_body3 = json_data3["body"]
    json_str_3_3 = json_body3["items"]
    json_str_3_4 = json_str_3_3["item"]
     
    if json_str_3_1 == "ERROR_2001" :
        json_str_3_5 = json_str_3_4["serviceKey"]
    else :
        for i in range(0len(json_str_3_4)):
            json_str_3_5 = '<br>' + json_str_3_4[i]["serviceKey"]
    json_str_3_6 = ''
    if json_str_3_1 == "ERROR_2001" :
        json_str_3_6 = json_str_3_6 + '<br>' + json_str_3_4["transParm"]
    else :
        for i in range(0len(json_str_3_4)):
            json_str_3_6 = json_str_3_6 + '<br>' + json_str_3_4[i]["transParm"]
    resp3_body = 'resultCode : ' + json_str_3_1
    resp3_body = resp3_body +'<br> resultMsg : ' + json_str_3_2 + '<br> serviceKey : ' +json_str_3_5 +'<br> transParm :' +json_str_3_6
     
    html = '계란 이력번호 발급'+'<br>'+resp1_body+'<br><br><br>'+'계란 선별포장실적신고'+'<br>'+ resp2_body+'<br><br><br>'+'계란 거래신고'+'<br>'+ resp3_body
    # Turn these into plain/html MIMEText objects
    html_part = MIMEText(html, "html")
     
    # Add HTML/plain-text parts to MIMEMultipart message
    # The email client will try to render the last part first
    message.attach(html_part)
     
    # 메일 보내기
    s.sendmail("이메일주소""비밀번호키", message.as_string())
     
    # 세션 종료
    cs







💡 아래 참고자료 한번 읽어보세요.
                ↓↓↓





전체 스크립트 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import requests, json
from requests.structures import CaseInsensitiveDict
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
url = "http://api.mtrace.go.kr/rest/dfts/trace/transParam"
 
headers = CaseInsensitiveDict()
headers["Accept"= "application/json"
headers["charset"= "UTF-8"
headers["Content-Type"= "application/json"
 
report_date = datetime.today().strftime("%Y%m%d")
trace_num = "3"+datetime.today().strftime("%m%d")+"농장식별번호0001"
 
data1 = {"userId""000000",
        "apiKey""00000000000000000000",
        "serviceKey""addEggHistNo",
        "item": [{"transParam":trace_num+"|0000000000|00000000000|"+report_date+"|0000000000|00000000000|사업자명|대표자명|전화번호|핸드폰번호|주소|N|N|N|N|N|202239|OY2BC|사업자명|대표자명|N|N|N|N|N|N|314001|"+report_date+"||315002|||0|0|0|300|0|0|"}]
        }
 
data2 = {"userId""000000",
        "apiKey""00000000000000000000",
        "serviceKey""addEggPackng",
        "item": [{"transParam":"0000000000|00000000000|"+trace_num+"|"+report_date+"|"+report_date+"|260012|0000000000|00000000000|사업자명|대표자명|전화번호|핸드폰번호|주소|N|N|N|N|N|202239|고유번호|사업자명|대표자명|N|N|N|N|N|N|314001|"+report_date+"||0|0|0|300|0|0||315002|||0|0|0|290|0|0|||"}]
        }
 
data3 = {"userId""000000",
        "apiKey""00000000000000000000",
        "serviceKey""addEggTrade",
        "item": [
                        {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|120|0|0||N||||"},
                        {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|120|0|0||N||||"},
                        {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|30|0|0||N||||"},
                        {"transParam":"0000000000 |00000000000||309002|"+report_date+"|002|260002|0000000000|00000000000||판매정명|대표자명|||주소|"+trace_num+"|314001|"+report_date+"|0|0|0|20|0|0||N||||"}
                ]
        }
 
data_EggHistNo = json.dumps(data1).encode('utf8')
data_EggPackng = json.dumps(data2).encode('utf8')
data_EggTrade = json.dumps(data3).encode('utf8')
 
resp1 = requests.post(url, headers=headers, data=data_EggHistNo)
resp2 = requests.post(url, headers=headers, data=data_EggPackng)
resp3 = requests.post(url, headers=headers, data=data_EggTrade)
 
#print(resp1.status_code)
#print(resp1.text)
#print(resp2.status_code)
#print(resp2.text)
#print(resp3.status_code)
#print(resp3.text)
 
# 세션 생성
= smtplib.SMTP('smtp.gmail.com'587)
 
# TLS 보안 시작
s.starttls()
 
# 로그인 인증
s.login('구글이메일''비밀번호키')
 
# create MIMEBase
send_time = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
message = MIMEMultipart("alternative")
message["Subject"= send_time+' eggTrace.py가 실행되었습니다.'
 
# Create the plain-text and HTML version of your message
#addEggHistNo
json_data1 = json.loads(resp1.text)
json_header1 = json_data1["header"]
json_str_1_1 = json_header1["resultCode"]
json_str_1_2 = json_header1["resultMsg"]
 
json_body1 = json_data1["body"]
json_str_1_3 = json_body1["items"]
json_str_1_4 = json_str_1_3["item"]
json_str_1_5 = json_str_1_4["serviceKey"]
json_str_1_6 = json_str_1_4["transParm"]
 
resp1_body = '이력번호 : ' + trace_num + '<br>신고일자 : ' +report_date + '<br><br>resultCode : ' + json_str_1_1
resp1_body = resp1_body +'<br> resultMsg : ' + json_str_1_2 + '<br> serviceKey : ' +json_str_1_5 +'<br> transParm : <br>' +json_str_1_6
 
#addEggPackng
json_data2 = json.loads(resp2.text)
json_header2 = json_data2["header"]
json_str_2_1 = json_header2["resultCode"]
json_str_2_2 = json_header2["resultMsg"]
 
json_body2 = json_data2["body"]
json_str_2_3 = json_body2["items"]
json_str_2_4 = json_str_2_3["item"]
json_str_2_5 = json_str_2_4["serviceKey"]
json_str_2_6 = json_str_2_4["transParm"]
 
resp2_body = 'resultCode : ' + json_str_2_1
resp2_body = resp2_body +'<br> resultMsg : ' + json_str_2_2 + '<br> serviceKey : ' +json_str_2_5 +'<br> transParm : <br>' +json_str_2_6
 
#addEggTrade
json_data3 = json.loads(resp3.text)
json_header3 = json_data3["header"]
json_str_3_1 = json_header3["resultCode"]
json_str_3_2 = json_header3["resultMsg"]
 
json_body3 = json_data3["body"]
json_str_3_3 = json_body3["items"]
json_str_3_4 = json_str_3_3["item"]
 
if json_str_3_1 == "ERROR_2001" :
    json_str_3_5 = json_str_3_4["serviceKey"]
else :
    for i in range(0len(json_str_3_4)):
        json_str_3_5 = '<br>' + json_str_3_4[i]["serviceKey"]
json_str_3_6 = ''
if json_str_3_1 == "ERROR_2001" :
    json_str_3_6 = json_str_3_6 + '<br>' + json_str_3_4["transParm"]
else :
    for i in range(0len(json_str_3_4)):
        json_str_3_6 = json_str_3_6 + '<br>' + json_str_3_4[i]["transParm"]
resp3_body = 'resultCode : ' + json_str_3_1
resp3_body = resp3_body +'<br> resultMsg : ' + json_str_3_2 + '<br> serviceKey : ' +json_str_3_5 +'<br> transParm :' +json_str_3_6
 
html = '계란 이력번호 발급'+'<br>'+resp1_body+'<br><br><br>'+'계란 선별포장실적신고'+'<br>'+ resp2_body+'<br><br><br>'+'계란 거래신고'+'<br>'+ resp3_body
# Turn these into plain/html MIMEText objects
html_part = MIMEText(html, "html")
 
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(html_part)
 
# 메일 보내기
s.sendmail("이메일주소""비밀번호키", message.as_string())
 
# 세션 종료
s.quit()
cs


댓글 쓰기

1 댓글

  1. 좋은 글 감사합니다. 정부에서 이런걸 풀어놓은줄 모르고, 셀레늄으로 해결해야하나 막막했었는데, 일반적인 REST API 요청으로도 할 수 있었군요. 복받으십시오.

    답글삭제