파이썬/파이썬(python) 중급

[37-1 파이썬] 1단계 pixela 사용자 계정 생성하기, HTTP Requests(get, post, put, delete)

Olivia-BlackCherry 2022. 9. 29. 07:45

우리는 이제까지 Requests 모듈로 인터넷을 통해 http를 요청했다.  

requests.get()으로

외부 시스템에 데이터를 요청하면, 외부시스템이 관련 데이터에 대한 응답을 주었다.

 

오늘은 get 요청(requests) 외에 post, put, delete  요청을 배워보도록 하자.

 

request.post()

성공, 실패 여부를 제외하고는 시스템으로 받는 응답이 크게 중요하지 않다. 

예를 들어 facebook, twitter, googlesheet 등에 내가 원하는 데이터를 게시하는 경우에 쓴다.

 

requests.put()

외부시스템에 게시 된 글을 업데이트 하는 경우이다.

 

requests.delete()

외부시스템에 게시된 글을 삭제하는 경우이다. 

 

 

지금부터

pixela에서 제공하는 api를 이용하여 requests 모듈을 실습해본다.

홈페이지에 들어가면 API를 어떻게 이용할 수 있는지

친절한 설명이 되어 있다. 

https://pixe.la/

 

Pixela | Record and Track your habits or effort. All by API.

Pixela, Record and Track your habits or effort. All by API. | Pixela is the API service. With this service, you can get a GitHub like graph that expresses the degree of your daily various activities on a basis with a vivid gradation. All operations are per

pixe.la

 

 

 

1단계
pixela에 내가 만든 username, token을 이용해 새 계정을 만들고, requests.post()를 해보자

- endpoint(URL)

https://pixe.la/v1/users

- API 다큐먼트

- post의 필수 파라미터

token: 사용자 인증으로 고유한 나를 확인할 수 있는 것으로서 api key와 같은 역할이다.

단지 특이점은, 내가 직접 생성한다. 8~128자 사이면 된다. 

패스워드라고 생각하면 된다.

username: 사용자 이름

agreeTermsOfService: 서비스에 관한 정책에 동의하는지 여부 yes or no

notMinor: 미성년자가 아닌지 여부 yes(성인) or no(미성년자)

 

 

- requests.post(url =?, json=?)

url: endpoint(url)를 넣는다. 

json: 파라미터를 넣는다.

import requests

endpoint="https://pixe.la/v1/users"
parameters = {
    "token": "safjklasfd",
    "username":"oliviasfasf",
    "agreeTermsOfService":"yes",
    "notMinor": "yes"
}
response = requests.post(url =endpoint, json =parameters)
print(response.text)

>>{"message":"Success. Let's visit https://pixe.la/@oliviaasfa , it is your profile page!","isSuccess":true}

 

만약 이 상태에서 한번 더 실행하면?

기존에 username이 있기 때문에 실패한다는 메시지가 뜰 것이다.

>>{"message":"This user already exist.","isSuccess":false}