{"id":20619754,"url":"https://github.com/twtrubiks/django_rest_framework_swagger_tutorial","last_synced_at":"2025-09-04T13:34:23.046Z","repository":{"id":84518937,"uuid":"93166583","full_name":"twtrubiks/django_rest_framework_swagger_tutorial","owner":"twtrubiks","description":"django rest framework swagger tutorial","archived":false,"fork":false,"pushed_at":"2022-06-28T06:12:46.000Z","size":14,"stargazers_count":22,"open_issues_count":0,"forks_count":9,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-15T12:11:35.922Z","etag":null,"topics":["api-documentation","django-rest-framework","python","swagger","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/twtrubiks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-06-02T13:09:41.000Z","updated_at":"2023-04-25T01:48:04.000Z","dependencies_parsed_at":"2023-03-02T04:30:27.711Z","dependency_job_id":null,"html_url":"https://github.com/twtrubiks/django_rest_framework_swagger_tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_rest_framework_swagger_tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_rest_framework_swagger_tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_rest_framework_swagger_tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_rest_framework_swagger_tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/twtrubiks","download_url":"https://codeload.github.com/twtrubiks/django_rest_framework_swagger_tutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249067779,"owners_count":21207396,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-documentation","django-rest-framework","python","swagger","tutorial"],"created_at":"2024-11-16T12:12:26.885Z","updated_at":"2025-04-15T12:11:54.091Z","avatar_url":"https://github.com/twtrubiks.png","language":"Python","readme":"# django-rest-framework-swagger-tutorial\n\nDjango-REST-Swagger 基本教學\n\n* [Youtube Tutorial](https://youtu.be/ayTF26EIMFU)\n\n相信大家在網路上一定都看過 **API 文件**，\n\n那我們該如何撰寫 **API 文件** 給別人看呢 ？\n\n今天我要教大家使用 [drf-yasg](https://github.com/axnsan12/drf-yasg) 來完成他 ！！\n\n***溫馨小提醒***\n\n建議大家先對 [Django](https://github.com/django/django) 以及 [Django REST framework](http://www.django-rest-framework.org/) ( DRF ) 有基礎的知識。\n\n如果還不熟的人，可以先閱讀我之前寫的\n\n[Django 基本教學 - 從無到有 Django-Beginners-Guide](https://github.com/twtrubiks/django-tutorial)\n\n以及\n\n[Django-REST-framework 基本教學 - 從無到有 DRF-Beginners-Guide](https://github.com/twtrubiks/django-rest-framework-tutorial)\n\n先建立一些基本觀念，再來看這篇比較清楚。\n\n## 教學\n\n我們依照 [Django-REST-framework 基本教學 - 從無到有 DRF-Beginners-Guide](https://github.com/twtrubiks/django-rest-framework-tutorial) 這篇繼續延伸下去。\n\n請在你的命令提示字元 (cmd ) 底下輸入\n\n安裝 [drf-yasg](https://github.com/axnsan12/drf-yasg)\n\u003epip install drf-yasg\n\n### drf-yasg 設定\n\n***請記得要將 [drf-yasg](https://github.com/axnsan12/drf-yasg) 加入設定檔***\n\n請在 [settings.py](https://github.com/twtrubiks/django_rest_framework_swagger_tutorial/blob/master/django_rest_framework_swagger_tutorial/settings.py) 裡面的 **INSTALLED_APPS** 加入下方程式碼\n\n```python\nINSTALLED_APPS = (\n    ...\n    'django.contrib.staticfiles',\n    'drf_yasg',\n    'rest_framework',\n)\n```\n\n接著我們設定 Routers 路由 ，請將 [urls.py](https://github.com/twtrubiks/django_rest_framework_swagger_tutorial/blob/master/django_rest_framework_swagger_tutorial/urls.py) 增加一些程式碼\n\n```python\n......\n\nschema_view = get_schema_view(\n   openapi.Info(\n      title=\"Snippets API\",\n      default_version='v1',\n      description=\"Test description\",\n      terms_of_service=\"https://www.google.com/policies/terms/\",\n      contact=openapi.Contact(email=\"contact@snippets.local\"),\n      license=openapi.License(name=\"BSD License\"),\n   ),\n#    public=True,\n   public=False, # need login\n   permission_classes=[permissions.AllowAny],\n)\n\nurlpatterns = [\n    path('admin/', admin.site.urls),\n\n    # for rest_framework\n    path('api/', include(router.urls)),\n    # for rest_framework auth\n    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n\n    re_path('swagger(?P\u003cformat\u003e\\.json|\\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),\n    re_path('swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),\n    re_path('redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),\n]\n```\n\n最後執行 Django ，然後瀏覽 [http://127.0.0.1:8000/swagger/](http://127.0.0.1:8000/swagger/)\n\n你應該會看到如下圖 (如果你沒看到任何東西，可以點一下 **Show/Hide** )\n\n![alt tag](http://i.imgur.com/qY9pz8N.png)\n\n也可以瀏覽 [http://127.0.0.1:8000/redoc/](http://127.0.0.1:8000/redoc/)\n\n![alt tag](https://i.imgur.com/WsHAMmk.png)\n\n### 執行畫面\n\n畫面非常漂亮，功能也非常完善，\n\n我們可以在上面執行 **GET** , **POST** , **PUT** , **PATCH** , **DELETE** , 甚至可以直接看到執行結果，\n\n我介紹幾個給大家當範例，看完大家就會比較了解\n\n ***POST***\n\n點選編號 1 的地方，他會幫你把範例貼到左手邊，修改完值之後，直接按 **Try it out!**\n\n![](http://i.imgur.com/RtDc29v.png)\n\n接著你會發現下面有 Response ， 以這個範例來講，201 就是新增成功\n\n![](http://i.imgur.com/y0tSltJ.png)\n\n ***GET***\n\n 接著我們再去  **GET** ，我們剛剛新增的那筆的確有在裡面\n\n![](http://i.imgur.com/rKf0KdN.png)\n\n有沒有發現非常強大 :open_mouth:\n\n接下來你可能會擔心，這樣我的資料不就會被任何人任意操作?\n\n不用擔心，和之前介紹的 [授權 (Authentication)](https://github.com/twtrubiks/django-rest-framework-tutorial#授權-authentications-) 是一樣的。\n\n## 授權（ Authentication ）\n\n在 [urls.py](https://github.com/twtrubiks/django_rest_framework_swagger_tutorial/blob/master/django_rest_framework_swagger_tutorial/urls.py) 底下程式碼,\n\n```python\nurlpatterns = [\n    ......\n    # for rest_framework auth\n    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n    ......\n]\n```\n\n在 [views.py](https://github.com/twtrubiks/django_rest_framework_swagger_tutorial/blob/master/musics/views.py) 底下加入  **permission**\n\n```python\n# Create your views here.\nclass MusicViewSet(viewsets.ModelViewSet):\n    queryset = Music.objects.all()\n    serializer_class = MusicSerializer\n    permission_classes = (IsAuthenticated,)\n```\n\n在 [settings.py](https://github.com/twtrubiks/django_rest_framework_swagger_tutorial/blob/master/django_rest_framework_swagger_tutorial/settings.py) 底下加入下方程式碼\n\n設定 SWAGGER_SETTINGS 為使用 rest_framework login, logout\n\n```python\nSWAGGER_SETTINGS = {\n    'LOGIN_URL': 'rest_framework:login',\n    'LOGOUT_URL': 'rest_framework:logout'\n}\n```\n\n也要把 [urls.py](https://github.com/twtrubiks/django_rest_framework_swagger_tutorial/blob/master/django_rest_framework_swagger_tutorial/urls.py) 中的 public 設為 `False`.\n\n可參考 [https://drf-yasg.readthedocs.io/en/stable/settings.html](https://drf-yasg.readthedocs.io/en/stable/settings.html)\n\n執行 Django, 然後瀏覽 [http://127.0.0.1:8000/swagger/](http://127.0.0.1:8000/swagger/)\n\n你會發現，當你沒有登入的時候，你是看不到這些 API 的內容,\n\n![alt tag](http://i.imgur.com/b3rbEZw.png)\n\n登入之後你才有權限可以看到這些資料\n\n我的 帳號/密碼 設定為 twtrubiks/password123 ，\n\nSwagger 的基本介紹我們就介紹到這邊，更多的說明可以參考 [drf-yasg](https://github.com/axnsan12/drf-yasg)\n\n## 執行環境\n\n* Python 3.8\n\n## Reference\n\n* [Django](https://www.djangoproject.com/)\n* [Django-REST-framework](https://www.django-rest-framework.org/)\n* [drf-yasg](https://github.com/axnsan12/drf-yasg)\n\n## License\n\nMIT license\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fdjango_rest_framework_swagger_tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftwtrubiks%2Fdjango_rest_framework_swagger_tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fdjango_rest_framework_swagger_tutorial/lists"}