티스토리 뷰

728x90
반응형

1. 모델 정의하기
api_app/models.py에서 API 호출 이력을 저장할 모델을 정의합니다.

from django.db import models

class ApiCallHistory(models.Model):
    endpoint = models.URLField()
    method = models.CharField(max_length=10)
    response_status = models.IntegerField()
    timestamp = models.DateTimeField(auto_now_add=True)

 

모델을 정의한 후, 마이그레이션을 적용합니다.

python manage.py makemigrations
python manage.py migrate

 

2. API 호출을 위한 뷰 생성
api_app/views.py에서 API를 호출하고 이력을 저장하는 뷰를 생성합니다.

from django.shortcuts import render, redirect
import requests
from .models import ApiCallHistory

def call_api(request):
    if request.method == 'POST':
        endpoint = request.POST.get('endpoint')
        method = request.POST.get('method', 'GET').upper()
        
        try:
            if method == 'GET':
                response = requests.get(endpoint)
            else:
                response = requests.post(endpoint)
            
            # 호출 이력 저장
            ApiCallHistory.objects.create(
                endpoint=endpoint,
                method=method,
                response_status=response.status_code
            )
            
            # 응답 표시
            return render(request, 'api_app/call_api.html', {'response': response.json()})
        except requests.exceptions.RequestException as e:
            return render(request, 'api_app/call_api.html', {'error': str(e)})
    
    return render(request, 'api_app/call_api.html')

 

3. 템플릿 생성하기
api_app/templates/api_app/call_api.html에 API 세부 정보를 입력하고 응답을 표시할 수 있는 폼을 생성합니다.

<h1>API 호출하기</h1>
<form method="post">
    {% csrf_token %}
    <label for="endpoint">API 엔드포인트:</label>
    <input type="text" name="endpoint" id="endpoint" required><br>
    
    <label for="method">메소드:</label>
    <select name="method" id="method">
        <option value="GET">GET</option>
        <option value="POST">POST</option>
    </select><br>
    
    <button type="submit">API 호출</button>
</form>

{% if response %}
<h2>응답:</h2>
<pre>{{ response }}</pre>
{% endif %}

{% if error %}
<h2>에러:</h2>
<p>{{ error }}</p>
{% endif %}

 

4. 이력을 표시할 뷰 생성
api_app/views.py에 API 호출 이력을 목록으로 표시할 뷰를 추가합니다.

 

def api_call_history(request):
    history = ApiCallHistory.objects.all().order_by('-timestamp')
    return render(request, 'api_app/api_call_history.html', {'history': history})

 

5.이력을 표시할 템플릿 생성
api_app/templates/api_app/api_call_history.html에서 API 호출 이력을 표시합니다.

<h1>API 호출 이력</h1>
<table>
    <tr>
        <th>시간</th>
        <th>엔드포인트</th>
        <th>메소드</th>
        <th>상태</th>
    </tr>
    {% for call in history %}
    <tr>
        <td>{{ call.timestamp }}</td>
        <td>{{ call.endpoint }}</td>
        <td>{{ call.method }}</td>
        <td>{{ call.response_status }}</td>
    </tr>
    {% endfor %}
</table>

 

 6. URL 설정하기
api_app/urls.py에 URL을 추가합니다:

from django.urls import path
from . import views

urlpatterns = [
    path('call_api/', views.call_api, name='call_api'),
    path('api_call_history/', views.api_call_history, name='api_call_history'),
]
메인 프로젝트의 urls.py에 위 URL들을 포함시킵니다.
python
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api_app/', include('api_app.urls')),
]

 

7. 서버 실행 후 결과 확인하기 
마지막으로 서버를 실행하고 애플리케이션을 테스트합니다.

python manage.py runserver


아래 URL에서 애플리케이션을 접근할 수 있습니다: 

http://localhost:8000/api_app/call_api/`와 http://localhost:8000/api_app/api_call_history/`.

 

728x90
반응형