0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

今回はDjango REST Frameworkで、ルーティングを使ってビュー(APIエンドポイント)とURLパターンを関連付けを学びます。

目次

  • 通常のルーティング
  • ルーターを使った自動ルーティング
  • カスタムルーター
  • 名前空間を使ったルーティング
  • まとめ(DRFのルーティング設定)

通常のルーティング

通常、Djangoでは、pathを使用してビューとURLを手動で関連付けます。
Class-based Views のルーティングの場合

# backend/profiles/urls.py

from django.urls import path
from.views import MyProfileView

urlpatterns = [
    path("profile/me/", MyProfileView.as_view(), name="my_profile"),
]

のようになります。

ルーターを使った自動ルーティング

ViewSetsを使う場合、DRFが提供するルーターを使用すると、CRUD操作を簡単に設定できます。

# backend/tweets/urls.py

from rest_framework.routers import DefaultRouter
from.views import TweetViewSet

router = DefaultRouter
router.register(r'tweets', TweetViewSet, basename='tweets')

urlpatterns = router.urls

上記のようにすると
DefaultRouterを使ったルーティングでは、
以下、ViewSetのエンドポイントを自動的に生成してくれます。

  • GET /tweets/: ユーザー一覧を取得
  • POST /tweets/: ユーザーを作成
  • GET /tweets/{id}/: 特定のユーザー詳細を取得
  • PUT /tweets/{id}/: 特定のユーザーを更新
  • DELETE /tweets/{id}/: 特定のユーザーを削除

以下のような、ルーターと通常のURLパターンの組み合わせも可能です。

# backend/tweets/urls.py

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from.views import TweetViewSet
from.users.views import UserAPIViewSet

router = DefaultRouter
router.register(r'tweets', TweetViewSet, basename='tweets')

urlpatterns = [
    path('user/', UserAPIViewSet.as_view(), name='user_list'),
    path('', include(router.urls)),
]

カスタムルーター

必要なエンドポイントだけを指定したい場合は、
SimpleRouterが用意されてたり、CustomRouterを使います。

SimpleRouterを使った例

SimpleRouter はブラウザ用のAPIルートを含まない、シンプルなルーターです。


from rest_framework.routers import DefaultRouter
from.views import TweetViewSet

router = SimpleRouter()
router.register(r'tweets', TweetViewSet, basename='tweets')

urlpatterns = router.urls

CustomRouterを使った例

特定のエンドポイントを追加するために、カスタムルーターを作成できます。


from rest_framework.routers import DefaultRouter
from.views import TweetViewSet

class CustomRouter(DefaultRouter):
     routes = [
        # 必要なルートをここに定義
    ]
    

名前空間を使ったルーティング

以下のように名前空間を使うことで、
アプリケーションごとにURLのスコープを明確にできます。


from django.urls import path
from.views import TweetViewSet
from.views import UserAPIViewSet

app_name = 'example'

urlpatterns = [
       path('user/', UserAPIViewSet.as_view(), name='user_list'), 
    ]

まとめ(DRFのルーティング設定)

ViewSetとルーターを活用
単純なCRUDエンドポイントはViewSetとルーターで設定すると効率的です。

カスタムビューとルーターの組み合わせ
複雑なビジネスロジックや特殊なエンドポイントは、APIViewでカスタマイズします。

名前空間を使う
名前空間を使うことで、大規模プロジェクトでもURLの競合を防ぎます。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?