Web制作、Web開発の歩き方

初心者のためのDjango入門

■第7話:APIサーバーとしてのDjango(Django REST Framework)

(最終更新日:2022.06.01)

Djangoフレームワークのイメージ
この記事は7分で読めます!
(絵が小さい場合はスマホを横に)

「APIってなに?」

「APIってよく聞くけど分からない。なんか難しそう。」「自分でも作れるの?」 プログラミングを始めたばかりの方はこう思うことも多いかもしれない。 今回はDjangoにおけるAPIサーバーの構築方法を説明する。


1RESTful APIとAPIサーバーの意義

まずはAPIの説明をする。 APIとは、Application Programming Interfaceの略で、プログラムを外部で共有できるように公開したものである。 Twitter等の有名なAPIを思い浮かべれば分かると思うが、 公開されているルールに従ってデータを送ればtweetすることもできるし、流れている情報を見ることもできる。 外部からこの範囲で使っていいですよという入口のようなイメージを持ってくれればと思う。 APIを使えば外部サービスを自分のサイトで利用することもできるし、自分のサービスを提供することもできる。

次にRESTの説明をする。 RESTには4つの原則というものがあって、2000年にロイ・フィールディングが提唱した。 あくまで原則なので厳密なルールではない。「この考え方に沿って作りましょう」というものである。 火事で避難する際の「おかしひも」のようなものだ。RESTについて詳しく知りたい方は、 このサイトを見てほしい。 データ形式はJSONに決まってる訳ではなく、XMLでもRESTに当てはまる。 ただし、一般的にRESTful APIと言ったらJSON形式でのやり取りを指すので、JSONを扱うと思って良いだろう。 普段使ってるHTTPがHTMLでやり取りするので、軽いデータ形式で送受信できるものだと考えれば良い。 REST APIサーバーとは、外部サービスとJSONでやり取りするものである。

下記に気象庁の予報データを利用する例を示す。スマホアプリでもブラウザでも簡単に東京都の天気の情報を利用できる。

APIの利用例

2.Django REST frameworkとDjangoの違い

前項でREST APIサーバーのイメージは沸いたと思う。 ここでは、DjangoのREST APIサーバー(Django REST framework)と通常のDjangoの違いについて説明する。 この点を理解するには、下記のような構造の違いを見るのが早いと思う。 第4話のDjangoのアーキテクチャーの図で示したように、urls.pyまでは構造が同じである。 ルーティング(urls.py)とモデル(models.py)の間が、ビュー(views.py)からapis.pyとserializers.pyに変わった所が異なる。

serializers.pyは、モデルから取得したデータをJSON形式に変換をする。 フィールド(項目)の選択もここで行う。

apis.pyは通常のDjangoのviews.pyに当たる部分である。 対象とするモデルを選択したり、データ変換のロジックを示したり、認証を定義したりする場所である。 CRUD操作の何を許可するかということも決めている。

urls.pyは通常のDjangoと共通であるが、ここはエンドポイント(接続場所)を示すことになる。 ここにアクセスすれば、データを送受信できるということである。

次項で実際の例を交えて説明する。

DjangoとDjango REST Frameworkの違い

3.Django REST frameworkの導入方法

Django REST Frameworkは別途、pipでのインストールが必要となる。「pip install djangorestframework」と入力してインストールしよう。 インストールしたら、setting.pyのINSTALLED_APPの一番最後に「'rest_framework'」と追加しよう。これで使う準備は万端だ。


4.Django REST frameworkの使い方

Django REST frameworkは実際以下のように記述する。 左上がModel、右上がSerializer、左下がAPIView(apis.py)、右下がurls.pyである。 ModelはTableの項目を定義していてDjangoと変わらない。Serializerでは、対象とするTableの項目を設定している。 APIViewでは、Serializerの選択や認証の設定をしている。urls.pyではJSONデータを取得できるエンドポイントを定めている。

Django REST Frameworkの記述例

実際、エンドポイントにアクセスして、データを取得した例が左下に示す。 エンドポイントへは、JavaScript(AxiosやAjax)でアクセスしてデータを取得、加工する。 ここでは都市のデータと天気、気温を取得して表示した。 また、右下はエンドポイントへ直接アクセスした時の表示である。 Django REST Frameworkは単なるJSONではなく、GUIも自動で生成してくれる。 このGUIを用いて権限情報やPOST時の挙動を調べることができる。

Django REST Frameworkの記述例


▼参考図書、サイト

 「現場で使えるDjango REST Framework の教科書」 横瀬明仁
APIを基礎からしっかりと学び、Django Rest Frameworkで天気情報を取得するアプリを作ろう  Udemy(大橋 亮太 古田 薫)
REST APIとは?ざっくりと理解してみる【初心者向け】  Wiz テックブログ
【Python】Web APIをDjango REST frameworkを用いて実装する方法  DXCEL WAVE
【入門編】Django REST frameworkとは?チュートリアルで解説 Udemyメディア


Django Tutorial for Beginners ■Episode 7: Django as an API Server (Django REST Framework) (Last updated: 2022.06.01) Image of the Django framework This article takes about 7 minutes to read! (If the image is small, try rotating your phone) “What is an API?” “I often hear the term API, but I don't really get it. It sounds difficult.” “Can I create one myself?” If you're just starting to learn programming, these thoughts are common. In this article, we'll explain how to build an API server using Django. [Contents] What is a RESTful API and Why Do We Need API Servers? Differences Between Django and Django REST Framework How to Install Django REST Framework How to Use Django REST Framework 1. What is a RESTful API and Why Do We Need API Servers? First, let’s talk about what an API is. API stands for Application Programming Interface, and it's a way to share parts of a program with the outside world. Think about public APIs like those from Twitter—you can tweet or get timeline data by following their published rules. It’s like a gateway saying “you can use this part externally.” APIs let you use external services in your own apps, or expose your own services to others. Now, let's explain REST. REST stands for Representational State Transfer and was proposed by Roy Fielding in 2000. It’s a set of guiding principles rather than strict rules—similar to basic evacuation rules like “stop, drop, and roll.” If you want to learn more about REST, visit this site. REST APIs don't have to use JSON; XML is also valid. However, most RESTful APIs today use JSON, so we’ll assume JSON going forward. Since HTTP is commonly used to send HTML, you can think of REST as using a lighter format like JSON to send/receive data. A REST API server, then, is something that exchanges JSON with external services. Below is an example using weather forecast data from the Japan Meteorological Agency. Whether using a smartphone app or browser, Tokyo’s weather can be retrieved easily. Example Use of an API 2. Differences Between Django and Django REST Framework Now that you understand what a REST API server is, let’s compare Django with Django REST Framework (DRF). The best way to understand the difference is to look at the structural comparison. As shown in Episode 4, the structure is the same up to `urls.py`. The difference is in the section between `urls.py` and `models.py`: instead of `views.py`, DRF uses `apis.py` and `serializers.py`. `serializers.py` converts data from models into JSON format. It also defines which fields to include. `apis.py` is equivalent to Django’s `views.py`. It defines which models are used, handles data transformations, and sets authentication. It also defines what kind of CRUD operations are allowed. `urls.py` remains the same as in Django, but it defines API endpoints—places where data can be sent or retrieved. In the next section, we’ll look at a practical example. Differences Between Django and Django REST Framework 3. How to Install Django REST Framework Django REST Framework must be installed separately using pip. Run `pip install djangorestframework` to install it. Then, add `'rest_framework'` to the end of the `INSTALLED_APPS` list in your `settings.py`. Now you’re ready to use it. 4. How to Use Django REST Framework Here’s an example of how Django REST Framework is structured: Top left: Model, Top right: Serializer, Bottom left: APIView (`apis.py`), Bottom right: `urls.py`. The Model defines table fields, just like in Django. The Serializer selects which fields from the model to use. The APIView sets the Serializer and handles authentication. `urls.py` defines the endpoints for retrieving JSON data. Example Code using Django REST Framework On the bottom left is an actual example of retrieving data from an endpoint. You can use JavaScript (e.g., Axios or Ajax) to access the endpoint, retrieve, and process the data. In this example, we retrieve and display city data along with weather and temperature. The bottom right shows how it looks when directly accessing the endpoint. Django REST Framework not only returns JSON but also generates a GUI. You can use this GUI to check authorization or test POST operations. Django REST Framework App Example ▼References  “Practical Guide to Django REST Framework” by Akihito Yokose   Learn API from the Basics and Build a Weather App with Django REST Framework — Udemy (Ryota Ohashi, Kaoru Furuta)   What is REST API? An Easy Introduction for Beginners — Wiz Tech Blog   [Python] How to Build a Web API with Django REST Framework — DXL WAVE   [Beginner’s Guide] What is Django REST Framework? Explained with a Tutorial — Udemy Media