섹션2: Build Your First REST API with Django

천호영·2021년 6월 9일
0

APIs, JSON and ENDPOINTS

API = Application Programming Interface.

API는 다른 software component간의 communication 방법입니다.
API가 interface를 정의하고, 우리는 API중에서 Web API에 대해 살펴봅니다.

가장 많이 쓰이는 Web API는 REST입니다. 우리는 REST API를 만들어 볼 것입니다.
API를 가장 처음 접하게 만들면, common interface가 되어 매우 편해집니다.

JSON = JavaScript Object Notation

API에서 소통하는데 가장 많이 쓰이는 file format은 JSON입니다.

API들에는 URL patterns와 같은 Endpoints를 통해 access합니다.

REST, HTTP and STATUS CODES

REST = REpresentational State Transfer

REST는 HTTP를 communication protocol로 사용하며, 다음 기준을 만족합니다.

  1. URL endpoints를 통해 resouce에 접근
  2. fileformat으로 JSON이나 XML을 사용
  3. Stateless(한 request가 다른 request에 의존X)
  4. GET, POST, PUT, DELETE의 HTTP verb를 통해 action 수행

HTTP = HyperText Transfer Protocol

HTTP는 웹상에서 정보를 전달할때 쓰이는 내우 중요한 protocol입니다.

HTTP request method
1. GET: retrieve a resource
2. POST: create a new resource
3. PUT/PATH: update a resource
4. DELETE: delete a resource

Status Code
1xx: Information
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error

The Requests Module

Requests Module을 통해 HTTP requests를 보낼 수 있습니다.

<가상환경 설정 & requests install>

python -m venv venv
venv\Scripts\activate
pip install requests
#vscode에서 venv의 python을 interpreter로 선택
pip install pylint

<requests.get()으로 response받아오고, response내용 모두 접근가능>

import requests

def main():
    response = requests.get("http://www.google.com")
    # response = requests.get("http://www.google.com/random-address/")
    print("Status Code: ", response.status_code)
    # print("Headers: ", response.headers)
    # print("'Content-Type': ", response.headers['Content-Type'])
    print("Content: ", response.text)


if __name__ == "__main__":
    main()

<response.json()을 통해 json형식으로 response변환>

import requests

def main():
    response = requests.get("https://api.exchangeratesapi.io/latest")
    
    if response.status_code != 200:
        print("Status Code: ", response.status_code)
        raise Exception("There was an error!")

    data = response.json()
    print("JSON data: ", data)



if __name__ == "__main__":
    main()

<parameter를 dictionary에 담아서 전달>

import requests

def main():
    # response = requests.get("https://api.exchangeratesapi.io/latest?base=USD&symbols=GBP")

    payload = {"base": "USD", "symbols": "SEK"}
    response = requests.get("https://api.exchangeratesapi.io/latest",
                            params=payload)
    
    if response.status_code != 200:
        print("Status Code: ", response.status_code)
        raise Exception("There was an error!")

    data = response.json()
    print("JSON data: ", data)



if __name__ == "__main__":
    main()

Your First Django API (Pure django)

pip install django
pip install pillow #이미지 처리 위해
pip freeze > requirements.txt

django-admin startproject onlinestore . #프로젝트 생성
python manage.py migrate
python manage.py createsuperuser
python manage.py startapp products #INSTALL_APPS에 바로 추가해줘야함

0개의 댓글

관련 채용 정보