Python, OpenAPi

이도현·2023년 8월 10일
0

파이썬 공부

목록 보기
2/7

1. OpenAPI(Open Application Programming interfcae)

  • 애플리케이션 , 시스템, 기술 등 간에 상호 작용하기 위한 인터페이스 규약
  • 다른 개발자나 기업에서 제공하는 서비스나 데이터 등을 간편하게 활용할 수 있으며, 이를 통해 더욱 다양하고 풍부한 애플리케이션을 개발할 수 있습니다.

2. OpenWeater

  • 날씨 데이터와 관련된 서비스를 제공하는 회사
  • OpenWeather의 API 는 JSON 형식으로 응답하며, 세계 각지의 지리적 위치에서 날씨 데이터를 제공합니다. 또한 이 회사는 클라우드 기반의 날씨 모니터링 및 예측 서비스를 제공합니다.
  • https://openweathermap.org/
    - 회원가입 → 로그인
    - API키 발급: 회원 가입시 자동 발급
{
	"coord": { "lon": 126.9778, "lat": 37.5683 },
	"weather": [
		{ "id": 800, "main": "Clear", "description": "맑음", "icon": "01d" }
	],
	"base": "stations",
	"main": {
		"temp": 272.82,
		"feels_like": 268.77,
		"temp_min": 272.15,
		"temp_max": 273.15,
		"pressure": 1028,
		"humidity": 34
	},
	"visibility": 10000,
	"wind": { "speed": 1.03, "deg": 120 },
	"clouds": { "all": 0 },
	"dt": 1612420804,
	"sys": {
		"type": 1,
		"id": 8105,
		"country": "KR",
		"sunrise": 1612391603,
		"sunset": 1612429114
		},
	"timezone": 32400,
	"id": 1835848,
	"name": "Seoul",
	"cod": 200
}

3. 파이썬 requests 모듈

  • http 통신을 지원하는 모듈
    • Web openApi 호출에 사용
  • 설치
    • pip install requests
  • 사용법
    • res = requests.HTTP_메소드(URL, [headers=], [data=])
    • res = requests.post(url, data-obj_dict)
    • res = requests.put(url, data = obj_dict)
    • res = requests.delete(url)
  • Response 객체
  • requests 요청의 리턴값
    • status_code 응답 상태 코드(200, 404, 501…)
    • headers 응답 헤더
    • cookies 쿠키 목록
    • encoding 응답 데이터(body) 인코딩 방식
    • text 텍스트 응답 데이터(html, txt …)
    • content 바이너리 응답 데이터(images, audio, video..)
    • .json() json문자열을 해석해서 dict 타입 리턴

4. GET 요청 보내기

import requests

url = "http://www.naver.com"
response = requests.get(url)
print("status code :", response.status_code)
print(response.text)
# 파일 다운로드
from requests import get

def download(url, file_name):
	with open(file_name,"wb") as file:
		response = get(url) # get request
		file.write(response.content) # write to file

if __name__ == '__main__':
	url = "https://cdn.arduino.cc/homepage/static/media/arduino_UNO.vcc69bed.png"
	download(url, "arduino.png")
  • url에서 파일명 추출하기
    • file_name = url.split(’/’)[-1]

5. JSON

  • JavaScript Object Notation
  • 문자열로 정보의 구조화를 표현
    • 자바스크립트 객체의 리터럴 표기방식과 동일
  • 파이썬에서는 사전과 유사
  • 규칙
    • 키이름은 반드시 큰 따옴표로 표기
    • 값의 표기
      • 문자열: 큰 따옴표로 표기
      • 숫자: 정수/실수 그대로 표기
      • boolean: true/false
      • 배열(리스트): []로 표기
  • 파이썬 json 모듈
    • 파이썬 표준 모듈
      • import json
    • json 해석 처리
      • dict 타임 <>json문자열 상호 변환
    • dict 타입 객체 → json 문자열 리턴
      • dump(dict_obj) : json 문자열 리턴
      • dump(file, dict_obj): json 문자열을 file에 저장
    • json 문자열 → dict 타입 객체 변환
      • loads(json_str): json 문자열을 분석하여 dict 타입 객체 반환
      • load(file): json file을 분석하여 dict 타입 객체 반환

6. weather.py

import requests as req
import json

API_KEY = '93ec9acd67f5e6d7fd08ff43c857eeac'

def get_weather(city='seoul'):
	URL = f'http://api.openweathermap.org/data/2.5/weather?q={city}&lang=kr'
	print(URL)
	weather = {}
	res = req.get(URL)
	if res.status_code == 200:
		result = res.json(URL)
		weather['main'] = result['weather'][0]['main']
		weather['description'] = result['weather'][0]['description']
		print(result['weather'][0]['description'])
		icon = result['weather'][0]['iocn']
		weather['icon'] = f'http://openweathermap.org/img/w/{icon}.png'
		wather['etc'] = result['main']
	else:
		print('error', res.status_code)
	
	return weather
weather = get_weather()
print(json.dumps(weather, indent = 4, ensure_ascii = False))
profile
좋은 지식 나누어요

0개의 댓글