0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Django REST Framework】外部APIをAPIViewで取得する

Last updated at Posted at 2022-01-09

Django REST FrameworkのAPIViewを使って外部APIを呼び出してみます。
今回はFinancial Modeling PrepをのSearchAPI(株式のシンボルを探すAPI)を使用しています。

<環境変数>
.env ⇒ settings.py ⇒ モジュール

##1.モジュールの作成

プロジェクト/lib/fmp_api.py
from django.conf import settings
import requests

API_KEY = settings.FMP_API_KEY
FMP_V3 = settings.FMP_V3

def search_symbol(keyword, limit=10, exchange=None):
    url = FMP_V3 + 'search'
    query = {
        'query': keyword,
        'limit': limit,
        'apikey': API_KEY
    }
    if exchange:
        query['exchange'] = exchange
    r = requests.get(url, params=query, timeout=2.0)
    if r.status_code == 200:
        data = r.json()
        return data
    else:
        return None

キーワードを指定すると10個のシンボルが返ってきます。
取引所の指定をする場合はexchangeを指定します。

##2.シリアライザの作成

アプリ/api/v1/views.py
from rest_framework import serializers

from profiles.models import FavoStock


class FMPSearchSymbolSerializer(serializers.Serializer):
    symbol = serializers.CharField(max_length=20)
    name = serializers.CharField(max_length=100)
    currency = serializers.CharField(max_length=3)
    stockExchange = serializers.CharField(max_length=100)
    exchangeShortName = serializers.CharField(max_length=15)
    user_has_liked_symbol = serializers.SerializerMethodField()

    def get_user_has_liked_symbol(self, instance):
        request = self.context.get('request')
        return FavoStock.objects.filter(profile=request.user.profile, symbol=instance['symbol']).exists()

お気に入りは別アプリのモデルからインポート。
登録があればtrue、なければfalseで返ってきます。

##3.クラスベースビューの作成

アプリ/api/v1/views.py
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response

from プロジェクト名.lib import fmp_api
from stocks.api.v1.serializers import FMPSearchSymbolSerializer

class SearchFMPSymbolAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request,kw):
        data = fmp_api.search_symbol(kw)
        if data:
            results = FMPSearchSymbolSerializer(data, many=True, context={"request": request})
            return Response(results.data)
        else:
            return Response(
                {
                    "error": {
                        "code": 404,
                        "message": "not found"
                    }
                },
                status = status.HTTP_404_NOT_FOUND
            )

日本語で探すとnot foundでレスポンスされます。

##4.URLの設定

アプリ/api/v1/urls.py
from django.urls import path, include
from stocks.api.v1.views import SearchFMPSymbolAPIView

urlpatterns = [
    path('search/<str:kw>/', SearchFMPSymbolAPIView.as_view(), name='search-symbol'),
]

あとはプロジェクトのurls.pyにアプリのurlsを追加して終了です。

##結果
結果が出力される場合↓
image.pngimage.png

エラーの場合↓
image.png

#参考
DjangoでAPI呼び出し
Django rest framework & external api

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?