Skip to content

Commit c6068c1

Browse files
committed
Finished docs chapter
1 parent d23aaff commit c6068c1

File tree

5 files changed

+56
-144
lines changed

5 files changed

+56
-144
lines changed

docs/coreapi.png

72.2 KB
Loading

docs/swagger.png

76.6 KB
Loading

docs/swagger.rst

Lines changed: 46 additions & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -1,176 +1,79 @@
1-
Documenting APIs with Swagger
2-
=============================
1+
Documenting APIs (with Swagger and more)
2+
==========================================================
33

4-
In this chapter we will see how to use swagger for all the views of our API.
4+
In this chapter we will see how to document our API.
5+
6+
As you build your API, you would need to document the API to collaborate with other people. In most companies and teams, the developer using the API is different from the one building them. API documentation and collaboration tools, become even more important in such an environment.
57

68
Swagger is a tool used to understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. In simple terms, with swagger you can see what all API end points are available for a web application. You can use swagger for testing the requests and responses of the API endpoints.
79

8-
Now lets us use swagger to our polls application.
10+
DRF comes with its own tool, coreapi, for documenting and interacting with the API.
911

10-
Hosting Swagger UI
11-
----------------------
12+
We will use both coreapi and swagger to document our API.
1213

13-
Firstly we need to host the swagger UI in order to view all the API endpoints. so we'll first clone the swagger UI from github.
1414

15-
.. code-block:: python
1615

17-
git clone
16+
Adding swagger documentation
17+
-----------------------------
18+
19+
Install django-rest-swagger
20+
21+
.. code-block:: bash
1822
19-
As swagger UI is a simple web application, you can host it using any of the hosting methods (apache, nginx, python's simple http server ) which you are familiar with.
23+
pip install django-rest-swagger
2024
21-
For simplicity purposes we'll use python's SimpleHTTPServer. Change the working directory to the above cloned folder i.e., swagger-ui and run the following command to start simple http server.
25+
Update your :code:`settings.py`
2226

2327
.. code-block:: python
2428
25-
cd swagger-ui
26-
python -m SimpleHTTPServer 8000
29+
INSTALLED_APPS = [
30+
# ...
31+
'polls',
32+
'rest_framework_swagger',
33+
]
2734
28-
Now that we have the swagger UI running and you can see this by going to url http://localhost:8000/ in your browser.
35+
Add swagger to your urls.
2936

37+
.. code-block:: python
3038
31-
JSON representation of the API
32-
---------------------------------
39+
from rest_framework_swagger.views import get_swagger_view
3340
34-
To view all the API endpoints, we need to specify them in a JSON file with the following format. You may call it pollaspi.json.
41+
schema_view = get_swagger_view(title='Polls API')
3542
36-
.. code-block:: python
43+
# ...
44+
urlpatterns = [
45+
# ...
46+
path(r'swagger-docs/', schema_view),
47+
]
3748
38-
{
39-
"swagger": "2.0",
40-
"info": {
41-
"description": "This is a sample server for polls api.",
42-
"version": "1.0.0",
43-
"title": "Polls API",
44-
"termsOfService": "http://example.com/terms/",
45-
"contact": {"email": "[email protected]"},
46-
"license": {"name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html"}
47-
},
48-
"host": "polls.example.com",
49-
"basePath": "/v2",
50-
"tags": [
51-
{
52-
"name": "polls",
53-
"description": "Everything about your Polls",
54-
"externalDocs": {"description": "Find out more","url":"http://example.com"}
55-
},
56-
{
57-
"name": "choices",
58-
"description": "Access to choices for the polls"
59-
},
60-
{
61-
"name": "user",
62-
"description": "Operations about user",
63-
"externalDocs": {"description": "Find out more about our store","url":"http://example.com"}
64-
}
65-
],
66-
"schemes": ["http"],
67-
"paths": {
68-
"/polls": {
69-
"get": {
70-
"tags": ["poll"],
71-
"summary": "Get all the polls",
72-
"description": "",
73-
"operationId": "pollList",
74-
"consumes": ["application/json","application/xml"],
75-
"produces": ["application/xml","application/json"],
76-
"parameters": [{
77-
"in": "query",
78-
"name": "body",
79-
"description": "Get all the polls.",
80-
"required": false,
81-
"schema":{"$ref":"#/pollsapi/Poll"}
82-
}],
83-
"responses": {"200":{"description":"Successfull operation"}},
84-
},
85-
"post":{
86-
"tags": ["poll"],
87-
"summary": "Create a new poll",
88-
"description": "Creates a new poll.",
89-
"operationId": "createPoll",
90-
"consumes":["application/json","application/xml"],
91-
"produces":["application/xml","application/json"],
92-
"parameters":[{
93-
"in":"query",
94-
"name":"body",
95-
"description": "Poll object that needs to be added.",
96-
"required": true,
97-
"schema": {"$ref":"#/pollsapi/Poll"}
98-
}],
99-
"responses": {
100-
"200": {"description":"Poll created successfully"}
101-
}
102-
}
103-
},
104-
"/choices": {
105-
"get": {
106-
"tags": ["choice"],
107-
"summary": "Get all the choices",
108-
"description": "",
109-
"operationId": "choiceList",
110-
"consumes": ["application/json","application/xml"],
111-
"produces": ["application/xml","application/json"],
112-
"parameters": [{
113-
"in": "query",
114-
"name": "body",
115-
"description": "Get all the choices.",
116-
"required": false,
117-
"schema":{"$ref":"#/pollsapi/Choice"}
118-
}],
119-
"responses": {"200":{"description":"Successfull operation"}},
120-
},
121-
"post":{
122-
"tags": ["choice"],
123-
"summary": "Create a new choice",
124-
"description": "Creates a new choice.",
125-
"operationId": "createChoice",
126-
"consumes":["application/json","application/xml"],
127-
"produces":["application/xml","application/json"],
128-
"parameters":[{
129-
"in":"query",
130-
"name":"body",
131-
"description": "Choice object that needs to be added.",
132-
"required": true,
133-
"schema": {"$ref":"#/pollsapi/Poll"}
134-
}],
135-
"responses": {
136-
"200": {"description":"Poll created successfully"}
137-
}
138-
}
139-
}
140-
}
141-
}
142-
143-
144-
This JSON file should also be available/hosted somewhere in order to access from swagger UI.
145-
146-
Lets use the same python's SimpleHTTPServer for hosting this JSON file but on a different port. In your terminal cd to the directory where the JSON file is located and run the following command.
49+
And your swagger docs are ready in all their glory.
50+
51+
.. image:: swagger.png
14752

148-
.. code-block:: python
14953

150-
python -m SimpleHTTPServer 8001
54+
Using coreapi for documentation
55+
--------------------------------
15156

15257

153-
Now open the swagger UI in your browser from http://localhost:8000/ and enter http://localhost:8000/pollsapi.json in the url textbox and click explore to view all the API endpoints of the service.
58+
Install coreapi
15459

60+
.. code-block:: bash
15561
156-
Note
157-
--------
62+
pip install coreapi
15863
159-
You may get errors while running both swagger and the JSON file with SimpleHTTPServer locally saying "It may not have the appropriate access-control-origin settings." That's because the server running swagger doesn't have access over the other server. In order to resolve this, we need give the access control. We can do this by writing a custom class and running the server using this. We'll write the custom class in a separate file called simple-cors-http-server.py.
16064
65+
Add coreapi urls to your urls.
16166

16267
.. code-block:: python
16368
164-
#! /usr/bin/env python2
165-
from SimpleHTTPServer import SimpleHTTPRequestHandler
166-
import BaseHTTPServer
69+
from rest_framework.documentation import include_docs_urls
70+
# ...
16771
168-
class CORSRequestHandler (SimpleHTTPRequestHandler):
169-
def end_headers (self):
170-
self.send_header('Access-Control-Allow-Origin', '*')
171-
SimpleHTTPRequestHandler.end_headers(self)
72+
urlpatterns = [
73+
# ...
74+
path(r'docs/', include_docs_urls(title='Polls API')),
75+
]
17276
173-
if __name__ == '__main__':
174-
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
77+
And your coreapi docs are ready in all their glory.
17578

176-
Now we may run this (simple-cors-http-server.py) file to serve the JSON file, which will allow swagger UI to access this file.
79+
.. image:: coreapi.png

pollsapi/polls/urls.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@
44

55
from rest_framework.routers import DefaultRouter
66

7+
from rest_framework.documentation import include_docs_urls
8+
9+
from rest_framework_swagger.views import get_swagger_view
10+
11+
schema_view = get_swagger_view(title='Polls API')
12+
13+
714
router = DefaultRouter()
815
router.register('polls', PollViewSet, base_name='polls')
916

@@ -13,6 +20,8 @@
1320
path("users/", UserCreate.as_view(), name="user_create"),
1421
path("polls/<int:pk>/choices/", ChoiceList.as_view(), name="polls_list"),
1522
path("polls/<int:pk>/choices/<int:choice_pk>/vote/", CreateVote.as_view(), name="polls_list"),
23+
path(r'docs/', include_docs_urls(title='Polls API')),
24+
path(r'swagger-docs/', schema_view),
1625
]
1726

1827
urlpatterns += router.urls

pollsapi/pollsapi/settings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
'rest_framework',
4949
'rest_framework.authtoken',
5050
'polls',
51-
51+
'rest_framework_swagger',
5252
]
5353

5454
MIDDLEWARE = [

0 commit comments

Comments
 (0)