› Spec
CPU: Apple M1 or Intel i5
RAM: 8GB
Storage: 256GB SSD
OS: macOS or Windows 11
Python: 3.11.5 and 3.8.7
Python_venv_path: Only /desktop/[folder]
IDE: Visual Studio Code
› Home › About › Archive › Categories › Guestbook

Categories : Python

Django Requests 세팅


  1. 장고API의 리퀘스트 세팅 및 예시 코드
    1. 0. 소개
    2. 1. 데이터 추가
    3. 2. 데이터 조희
    4. 3. 데이터 수정
    5. 4. 데이터 삭제

장고API의 리퀘스트 세팅 및 예시 코드

0. 소개

관련글 : Django 기본 구축하기
이전 Django 데이터에서 진행했던 기본API 세팅의 Requests 의 코드를 작성하는 글

import requests

1. 데이터 추가

url = 'http://localhost:8000/api/board/'
data = {
    'name': 'New Post',
    'description': 'This is the content of the new post.'
}

response = requests.post(url, data=data)

if response.status_code == 201:
    print('New post created:', response.json())
else:
    print('Failed to create new post:', response.status_code)


2. 데이터 조희

  • 전체 데이터 조회
url = f'http://localhost:8000/api/board/'

response = requests.get(url)

if response.status_code == 200:
    print('Board Detail:', response.json())
else:
    print('Failed to retrieve board detail:', response.status_code)
  • 선택 데이터 조회
post_id = 1  # 조회할 데이터의 ID
url = f'http://localhost:8000/api/board/{post_id}/'

response = requests.get(url)

if response.status_code == 200:
    print('Board Detail:', response.json())
else:
    print('Failed to retrieve board detail:', response.status_code)


3. 데이터 수정

post_id = 1  # 수정할 데이터의 ID
url = f'http://localhost:8000/api/board/{post_id}/'
data = {
    'title': 'Updated Post',
    'content': 'This is the updated content of the post.'
}

response = requests.put(url, data=data)

if response.status_code == 200:
    print('Post updated:', response.json())
else:
    print('Failed to update post:', response.status_code)


4. 데이터 삭제

post_id = 1  # 삭제할 데이터의 ID
url = f'http://localhost:8000/api/board/{post_id}/'

response = requests.delete(url)

if response.status_code == 204:
    print('Post deleted successfully')
else:
    print('Failed to delete post:', response.status_code)




확대 이미지