SlideShare a Scribd company logo
1 of 86
Download to read offline
PyCon Korea 2019
AITRICS
REST API
5 

Python backend app 

Flask 2 Django
●REST API 

●OpenAPI Specification

●Python Web Applications & OpenAPI Specification

●Django API 

●Flask API
REST API
REST API ?
HTTP
METHODS
https://api.example.com/speakers https://api.example.com/speakers/1
GET 1
POST -
PUT
request body
request body field null
1 request body
request body field null
PATCH
request body
request body field
1 request body
request body field
DELETE 1
OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
Representational State Transfer
( API )
REST API
OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
●API , 

●Host, port

● 

●URI

●URI HTTP method 

● request header, body

● response status code, body
REST API
OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
REST API
OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
..



● ..

● 

●
REST API
OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
OpenAPI Specification
RESTful API 

JSON, YAML 

API , / 

Swagger OpenAPI Initiative
OpenAPI Specification
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
API 

toolset 

●Swagger Codegen

●Swagger Editor

●Swagger UI

Swagger UI
●OpenAPI JSON/YAML 

API
Swagger?
https://petstore.swagger.io/
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
API 

toolset 

●Swagger Codegen

●Swagger Editor

●Swagger UI

Swagger UI
●OpenAPI JSON/YAML 

API
Swagger?
https://petstore.swagger.io/
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
API 

toolset 

●Swagger Codegen

●Swagger Editor

●Swagger UI

Swagger UI
●OpenAPI JSON/YAML 

API
Swagger?
https://petstore.swagger.io/
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
API 

toolset 

●Swagger Codegen

●Swagger Editor

●Swagger UI

Swagger UI
●OpenAPI JSON/YAML 

API
Swagger?
https://petstore.swagger.io/
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
API 

toolset 

●Swagger Codegen

●Swagger Editor

●Swagger UI

Swagger UI
●OpenAPI JSON/YAML 

API
Swagger?
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
https://petstore.swagger.io/
title: Sample PyCON speaker API

description: This is a sample server for a PyCON speaker management.

termsOfService: http://example.com/terms/

contact:

name: API Support

url: http://www.example.com/support

email: support@example.com

license:

name: MIT

version: 1.0.1
OpenAPI Specification YAML
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
servers:

- url: https://pycon-speaker.com:{port}/{basePath}

description: The production API server

variables:

port:

enum:

- '443'

- '8443'

default: '8443'

description: 8443 is for demo.

basePath:

default: v2
OpenAPI Specification YAML
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
paths:

/speakers:

get:

description: Returns all speakers from the system that the user has access to

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
OpenAPI Specification YAML
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
components:

schemas:

Speaker:

required:

- id

- email

properties:

id:

type: integer

format: int64

email:

type: string

name:

type: string

OpenAPI Specification YAML
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
OpenAPI Specification YAML
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
OpenAPI Specification

JSON / YAML
APISwagger UI
paths:

/speakers:

get:

description: Returns all speakers from the system
that the user has access to

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
Python Web Application & 

OpenAPI Specification
Generating OpenAPI YAML
Web Application Server
●Server information

○Base URL, port, ...

●Routing information

○ path 

●Request params

●Response schema
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Generating OpenAPI YAML
servers:

- url: https://pycon-speaker.com:{port}/{basePath}

description: The production API server

variables:

port:

enum:

- '443'

- '8443'

default: '8443'

description: 8443 is for demo.

basePath:

default: v2
Web Application Server
●Server information

○Routing information

■ Request params

■ Response schema
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Generating OpenAPI YAML
paths:

/speakers:

get:

description: Returns all speakers

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
Web Application Server
●Server information

○Routing information

■ Request params

■ Response schema
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Generating OpenAPI YAML
paths:

/speakers:

get:

description: Returns all speakers

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
Web Application Server
●Server information

○Routing information

■ Request params

■ Response schema
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Generating OpenAPI YAML
paths:

/speakers:

get:

description: Returns all speakers

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
Web Application Server
●Server information

○Routing information

■ Request params

■ Response schema
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Django & OAS
Django Server
●Server information → 

○Routing information → urls.urlpatterns

■ Request params → View, Model

■ Response schema → View, Model
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Django & OAS
Server Information
● ,


Routing Information
●urlpatterns
# urls.py

openapi_schema_view = get_schema_view(

openapi.Info(

title='Demo API',

default_version='v1',

),

url='https://demo.example.com:3000',

public=True,

)

urlpatterns = [

path('admin/', admin.site.urls),

path('docs/', openapi_schema_view.with_ui(...),

path('', include(router.urls)),

]
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Django & OAS
Request Params, Response Schema
●Function Based View
○ view request, response 

■ docstring ?

→ API
def speakers_list(request):

"""



response

- type: list

- content

- name: , string

- email: , string

- organization: , object

- name: , string

"""

...

return speakers
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
django/views/generics/edit.py
Django & OAS
Request Params, Response Schema
●Class Based View
○django/views/generics

○cls.model model 

→ response schema

○cls.get_form_class() form 

→ request parameters
CreateView
ModelFormMixin
get_form_class()
SingleObjectMixin
model
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Flask & OAS
Flask Server
●Server information → 

○Routing information → Flask.view_functions

■ Request params → View?, Model?

■ Response schema → View?, Model?
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Flask & OAS
Routing Information
●Flask.view_functions
# flask/app.py: Flask

def route(self, rule, **options):

def decorator(f):

endpoint = options.pop('endpoint', None)

self.add_url_rule(rule, endpoint, f, **options)

return f

return decorator

def add_url_rule(self, rule, endpoint, view_func, ...):

…

self.view_functions[endpoint] = view_func

…
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Flask & OAS
Request Params, Response Schema
●Function View (Django )
○ view request, response 

■ docstring ? → API 

●Pluggable View(Class Based View)
○Function View Extension
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
●Server information
○ 

●Routing information
○ framework routing 

●Request params
○(Django) View class form 

●Response schema
○(Django) View class model
REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
Django REST API
●APIView (Django view wrapping)

●ModelViewSet (generic views)

○Serializer

○Filterset

○Permission

●OpenAPI schema ( )
Django REST Framework
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
●APIView (Django view wrapping)

●ModelViewSet (generic views)

○Serializer
○Filterset

○Permission

●OpenAPI schema ( )
Django REST Framework
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
>>> speaker

<Speaker: Speaker object (1)>

>>> serializer = SpeakerSerializer(speaker)

>>> serializer.data

{'email': 'test@pycon.kr',

'name': 'test',

'created': '2019-08-18T12:15:10.375877'}
●APIView (Django view wrapping)

●ModelViewSet (generic views)

○Serializer
○Filterset

○Permission

●OpenAPI schema ( )
Django REST Framework
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
>>> data = {'email': 'another@pycon.kr',

'name': 'another test',

'created': '2019-08-18T12:16:10.375877'}

>>> serializer = SpeakerSerializer(data=data)

>>> serializer.is_valid()

True

>>> serializer.validated_data

{'email': 'another@pycon.kr',

'name': 'another test',

'created': datetime.datetime(2019, 08, 18, 12, 16, 10,
375877)}
●APIView (Django view wrapping)

●ModelViewSet (generic views)

○Serializer
○Filterset

○Permission

●OpenAPI schema ( )
Django REST Framework
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
>>> serializer.save()

<Speaker: Speaker object (2)>
●APIView (Django view wrapping)

●ModelViewSet (generic views)

○Serializer
○Filterset

○Permission

●OpenAPI schema ( )
Django REST Framework
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
API 

●Django REST Swagger

○ https://github.com/marcgibbons/django-rest-swagger

●DRF Yet another Swagger generator

○ https://github.com/axnsan12/drf-yasg

○ swagger/redoc UI
Django REST Framework
https://www.django-rest-framework.org/topics/documenting-your-api/

REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
API 

●Django REST Swagger

○ https://github.com/marcgibbons/django-rest-swagger

○ 2019-06-04 Deprecated…

●DRF Yet another Swagger generator

○ https://github.com/axnsan12/drf-yasg

○ swagger/redoc UI 

○
Django REST Framework
https://www.django-rest-framework.org/topics/documenting-your-api/

REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
●View serializer request / response schema 

● override decorator 

●OpenAPI Spec 2.0 schema 

○DRF OpenAPI schema
DRF-YASG
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF native vs DRF-YASG
# Django REST Framework (X)

responses:

'200':

content:

application/json:

schema:

properties:

id:

type: integer

readOnly: true

date:

type: string

format: date

packages:

type: array

items:

type: string
# DRF-YASG (O)

responses:

'200':

schema:

type: object

properties:

count:

type: integer

next:

type: string

format: uri

previous:

type: string

format: uri

results:

type: array

items:

$ref: '#/definitions/Record'
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF native vs DRF-YASG
# Django REST Framework (X)

responses:

'200':

content:

application/json:

schema:

properties:

id:

type: integer

readOnly: true

date:

type: string

format: date

packages:

type: array

items:

type: string
# DRF-YASG (O)

responses:

'200':

schema:

type: object

properties:

count:

type: integer

next:

type: string

format: uri

previous:

type: string

format: uri

results:

type: array

items:

$ref: '#/definitions/Record'
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
urlpatterns

(url → view class mappings)
/speakers → SpeakerViewSet
serializer class = SpeakerSerializer
/organizations → OrganizationViewSet
serializer class = OrganizationSerializer
DRF-YASG
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
urlpatterns
SpeakerViewSet
serializer class
Speaker

(id, name, email,
organization_id)
SpeakerSerializer
model = Speaker

id: int

name: str

email: str

organization_id: int, read-only

organization: 

OrganizationSerializer, write-only
DRF-YASG
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
urlpatterns
SpeakerViewSet
serializer class
SpeakerSerializer
model = Speaker

id: int

name: str

email: str

organization_id: int, read-only

organization: 

OrganizationSerializer, write-only
OrganizationSerializer
model = Organization

id: int

name: str
DRF-YASG
# drf_yasg/views.py

class SchemaView(APIView):

...

def get(self, request, version='', format=None):

...

schema = generator.get_schema(request, self.public)

...

return Response(schema)
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# drf_yasg/generators.py

class OpenAPISchemaGenerator:

def get_schema(self, request=None, public=False):

...

paths, prefix = self.get_paths(endpoints, ...)

...

return openapi.Swagger(

paths=paths,

...

)
def get_paths(self, endpoints, ...):

...

for url, (..., methods) in sorted(endpoints.items()):

...

for method, view in methods:

...

operation = self.get_operation(url, method, ...)

...

...

def get_operation(self, url, method, ...):

...

operation = view_inspector.get_operation(...)

...
urls.urlpatterns
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# drf_yasg/generators.py

class OpenAPISchemaGenerator:

def get_schema(self, request=None, public=False):

...

paths, prefix = self.get_paths(endpoints, ...)

...

return openapi.Swagger(

paths=paths,

...

)
def get_paths(self, endpoints, ...):

...

for path, (..., methods) in sorted(endpoints.items()):

...

for method, view in methods:

...

operation = self.get_operation(path, method, ...)

...

...

def get_operation(self, path, method, ...):

...

operation = view_inspector.get_operation(...)

...
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
paths:

/speakers:

get:

description: Returns all speakers

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
urls.urlpatterns
DRF-YASG
# drf_yasg/generators.py

class OpenAPISchemaGenerator:

def get_schema(self, request=None, public=False):

...

paths, prefix = self.get_paths(endpoints, ...)

...

return openapi.Swagger(

paths=paths,

...

)
def get_paths(self, endpoints, ...):

...

for url, (..., methods) in sorted(endpoints.items()):

...

for method, view in methods:

...

operation = self.get_operation(url, method, ...)

...

...

def get_operation(self, url, method, ...):

...

operation = view_inspector.get_operation(...)

...
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# drf_yasg/generators.py

class OpenAPISchemaGenerator:

def get_schema(self, request=None, public=False):

...

paths, prefix = self.get_paths(endpoints, ...)

...

return openapi.Swagger(

paths=paths,

...

)
def get_paths(self, endpoints, ...):

...

for path, (..., methods) in sorted(endpoints.items()):

...

for method, view in methods:

...

operation = self.get_operation(path, method, ...)

...

...

def get_operation(self, path, method, ...):

...

operation = view_inspector.get_operation(...)

...
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
paths:

/speakers:

get:

description: Returns all speakers

responses:

'200':

description: A list of speakers.

content:

application/json:

schema:

type: array

items:

$ref: '#/components/schemas/Speaker'
DRF-YASG
# drf_yasg/generators.py

class OpenAPISchemaGenerator:

def get_schema(self, request=None, public=False):

...

paths, prefix = self.get_paths(endpoints, ...)

...

return openapi.Swagger(

paths=paths,

...

)
def get_paths(self, endpoints, ...):

...

for path, (..., methods) in sorted(endpoints.items()):

...

for method, view in methods:

...

operation = self.get_operation(path, method, ...)

...

...

def get_operation(self, path, method, ...):

...

operation = view_inspector.get_operation(...)

...
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# drf_yasg/inspectors/view.py

class SwaggerAutoSchema(ViewInspector):

def get_operation(self, operation_keys=None):

...

parameters = body + query

parameters = filter_none(parameters)

parameters = self.add_manual_parameters(parameters)

...

responses = self.get_responses()



return openapi.Operation(

parameters=parameters,

responses=responses,

...

)

REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# drf_yasg/inspectors/view.py

class SwaggerAutoSchema(ViewInspector):

def get_operation(self, operation_keys=None):

...

parameters = body + query

parameters = filter_none(parameters)

parameters = self.add_manual_parameters(parameters)

...

responses = self.get_responses()



return openapi.Operation(

parameters=parameters,

responses=responses,

...

)

1. self.view serializer 

2. field inspector field 

○ Nested serializer

○ SerializerMethodField

○ Paginated response

3. openapi Response
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
●urlpatterns endpoints(url → view mapping) 

●endpoints iterate url, method request response 

●request response field inspector 

Nested serializer 

● request response OpenAPI schema
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# main/urls.py

...

openapi_schema_view = get_schema_view(

openapi.Info(

title='Demo API',

default_version='v1',

),

public=True,

)

urlpatterns = [

path('admin/', admin.site.urls),

path('docs/', openapi_schema_view.with_ui('redoc')),

path('', include(router.urls)),

]
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# main/models.py

class Speaker(models.Model):

id = AutoField(primary_key=True)

email = EmailField()

name = CharField(max_length=10, blank=True)

organization = ForeignKey(

Organization,

null=True,

on_delete=models.SET_NULL,

related_name='speakers'

)

# main/views.py

class SpeakerViewSet(ModelViewSet):

queryset = Speaker.objects.all()

serializer_class = SpeakerSerializer
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# main/serializers.py

class OrganizationSerializer(ModelSerializer):

...

class SpeakerSerializer(ModelSerializer):

organization = OrganizationSerializer(read_only=True,

help_text='Read-only ')

organization_id = PrimaryKeyRelatedField(source='organization',

queryset=Organization.objects.all(),

write_only=True,

help_text='Write-only ')

class Meta:

model = Speaker

fields = '__all__'

write_only_fields = ('organization_id',)

read_only_fields = ('organization',)
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
# main/serializers.py

class OrganizationSerializer(ModelSerializer):

...

class SpeakerSerializer(ModelSerializer):

organization = OrganizationSerializer(read_only=True,

help_text='Read-only ')

organization_id = PrimaryKeyRelatedField(source='organization',

queryset=Organization.objects.all(),

write_only=True,

help_text='Write-only ')

class Meta:

model = Speaker

fields = '__all__'

write_only_fields = ('organization_id',)

read_only_fields = ('organization',)
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
$ curl -X POST localhost:8000/speakers 

-d "name=test&email=test@pycon.kr&organization_id=1"

{

"id": 1,

"name": "test",

"email": "test@pycon.kr",

"organization": {

"id": 1,

"name": "test organization"

}

}
DRF-YASG
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG Custom Action
# main/views.py

class SpeakerViewSet(ModelViewSet):

queryset = Speaker.objects.all()

serializer_class = SpeakerSerializer

@action(methods=['get'], detail=False)

def count(self, _):

return Response({'result': Speaker.objects.count()})
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG Custom Action
Response schema 

!
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG Custom Action
# main/views.py

class SpeakerViewSet(ModelViewSet):

queryset = Speaker.objects

serializer_class = SpeakerSerializer

@swagger_auto_schema(

operation_description=' API',

responses={

'200': openapi.Response(

description='',

schema=openapi.Schema(

type='object',

properties={'result': openapi.Schema(type='integer')}

)

)

}

)

@action(methods=['get'], detail=False)

def count(self, _):

return Response({'result': Speaker.objects.count()})
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG Custom Action
# main/views.py

class SpeakerCountSerializer(Serializer):

result = IntegerField()

class SpeakerViewSet(ModelViewSet):

queryset = Speaker.objects

serializer_class = SpeakerSerializer

@swagger_auto_schema(

operation_description=' API',

responses={'200': SpeakerCountSerializer}

)

@action(methods=['get'], detail=False)

def count(self, _):

return Response({'result': Speaker.objects.count()})
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG Custom Action
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
● 

○read_only, write_only 

○serializer 

●Redoc UI request 

●Swagger UI 

●OpenAPI Spec 2.0
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
● 

○read_only, write_only 

○serializer 

●Redoc UI request 

●Swagger UI 

●OpenAPI Spec 2.0
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
DRF-YASG
● 

○read_only, write_only 

○serializer 

●Redoc UI request 

●Swagger UI 

●OpenAPI Spec 2.0
REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
https://swagger.io/blog/news/whats-new-in-openapi-3-0/
Flask REST API
●Resource View get, post 

●arg parser View 

●field model marshal
Flask-RESTful
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
●Flask-RESTful 

○ Flask-RESTful API 

● API 

●Flask-RESTful
Flask-RESTPlus
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
●Flask RESTful Swagger 2.0

○ OpenAPI Spec 1.2 

○ 2.0 

●SQLAlchemy Flask RESTful Swagger (SAFRS)

○ DB model class 

○ Model method docstring
API
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
Flask-RESTPlus
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
●Flask RESTful Swagger 2.0

○ OpenAPI Spec 1.2 

○ 2.0 

●SQLAlchemy Flask RESTful Swagger (SAFRS)

○ DB model class 

○ Model method docstring
Flask-RESTPlus
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
●Flask RESTful Swagger 2.0

○ OpenAPI Spec 1.2 

○ 2.0 

●SQLAlchemy Flask RESTful Swagger (SAFRS)

○ DB model class 

○ Model method docstring 

●Flask-RESTPlus 

Flask-RESTPlus
from flask import Flask

from flask_sqlalchemy import SQLAlchemy

from flask_restplus import Api

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

api = Api(app)

REST API OpenAPI Specification Python Web Apps & OAS Django Flask
Flask-RESTPlus
class OrganizationModel(db.Model):

id = db.Column(db.Integer, primary_key=True, autoincrement=True)

name = db.Column(db.String(100), nullable=False)

class SpeakerModel(db.Model):

id = db.Column(db.Integer, primary_key=True, autoincrement=True)

name = db.Column(db.String(10), nullable=True)

email = db.Column(db.String(120), unique=True, nullable=False)

organization_id = db.Column(db.Integer, db.ForeignKey('organization_model.id'))

organization = relationship('OrganizationModel')
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
Flask-RESTPlus
organization_output = api.model('OrganizationOutput', {

'name': fields.String

})

speaker_output = api.model('SpeakerOutput', {

'name': fields.String,

'email': fields.String,

'organization': fields.Nested(organization_output)

})

speaker_input = reqparse.RequestParser()

speaker_input.add_argument('email', type=str)

speaker_input.add_argument('name', type=str)

speaker_input.add_argument('organization_id', type=int)

REST API OpenAPI Specification Python Web Apps & OAS Django Flask
Flask-RESTPlus
@api.route('/speakers')

class Speaker(Resource):

@api.marshal_list_with(speaker_output)

def get(self):

return Speaker.query.all()

@api.expect(speaker_input)

@api.marshal_with(speaker_output)

def post(self):

args = speaker_input.parse_args()

speaker = SpeakerModel(**args)

db.session.add(speaker)

db.session.commit()

return speaker
$ curl -X POST localhost:5000/speakers 

-d "name=test&email=test@pycon.kr&organization_id=1"

{

"name": "test",

"email": "test@pycon.kr",

"organization": {

"name": "test organization"

}

}
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
Flask-RESTPlus
REST API OpenAPI Specification Python Web Apps & OAS Django Flask
●Web framework → OpenAPI YAML / JSON → Swagger / Redoc UI

● web framework(Bottle, Sanic, Vibora ) 

runtime routing (path → view function) 

○ OpenAPI schema 

○ Sanic-RESTPlus

●drf-yasg, Flask-RESTPlus
www.aitrics.com
contact@aitrics.com
Yongseon Lee <yongseon@aitrics.com>
● REST API (Yongseon Lee) 

18th (Sun) 11:55 ~ 12:35
● Advanced Python testing techniques (Jaeman An)

18th (Sun) 11:55 ~ 12:35
● Django Query Optimization (Soyoung Yoon)

18th (Sun) 13:55 ~ 14:35
● Pickle & Custom Binary Serializer (Young Seok Kim)

18th (Sun) 14:55 ~ 15:35
Talks from AITRICS

More Related Content

What's hot

[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향Young-Ho Cho
 
入門ClojureScript
入門ClojureScript入門ClojureScript
入門ClojureScriptsohta
 
そうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解する
そうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解するそうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解する
そうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解するshigeki_ohtsu
 
Building robust and friendly command line applications in go
Building robust and friendly command line applications in goBuilding robust and friendly command line applications in go
Building robust and friendly command line applications in goAndrii Soldatenko
 
Baidu push 연동하기
Baidu push 연동하기Baidu push 연동하기
Baidu push 연동하기Choulhyouc Lee
 
Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計Koichi Nagaoka
 
[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성NAVER D2
 
Event source 학습 내용 공유
Event source 학습 내용 공유Event source 학습 내용 공유
Event source 학습 내용 공유beom kyun choi
 
Git을 조금 더 알아보자!
Git을 조금 더 알아보자!Git을 조금 더 알아보자!
Git을 조금 더 알아보자!Young Kim
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교Woo Yeong Choi
 
Quic을 이용한 네트워크 성능 개선
 Quic을 이용한 네트워크 성능 개선 Quic을 이용한 네트워크 성능 개선
Quic을 이용한 네트워크 성능 개선NAVER D2
 
SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개
SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개
SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개CURVC Corp
 
"Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ..."Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ...Anton Babenko
 
【2000行弱!】x86用自作カーネルの紹介
【2000行弱!】x86用自作カーネルの紹介【2000行弱!】x86用自作カーネルの紹介
【2000行弱!】x86用自作カーネルの紹介Yuma Ohgami
 
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020Ji-Woong Choi
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기흥배 최
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...Amazon Web Services Korea
 
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기Chanwoong Kim
 

What's hot (20)

[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향
 
入門ClojureScript
入門ClojureScript入門ClojureScript
入門ClojureScript
 
そうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解する
そうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解するそうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解する
そうだったのか! よくわかる process.nextTick() node.jsのイベントループを理解する
 
Kubernetes
Kubernetes Kubernetes
Kubernetes
 
Building robust and friendly command line applications in go
Building robust and friendly command line applications in goBuilding robust and friendly command line applications in go
Building robust and friendly command line applications in go
 
Baidu push 연동하기
Baidu push 연동하기Baidu push 연동하기
Baidu push 연동하기
 
Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計
 
[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성[2D4]Python에서의 동시성_병렬성
[2D4]Python에서의 동시성_병렬성
 
Event source 학습 내용 공유
Event source 학습 내용 공유Event source 학습 내용 공유
Event source 학습 내용 공유
 
Git을 조금 더 알아보자!
Git을 조금 더 알아보자!Git을 조금 더 알아보자!
Git을 조금 더 알아보자!
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교
 
Quic을 이용한 네트워크 성능 개선
 Quic을 이용한 네트워크 성능 개선 Quic을 이용한 네트워크 성능 개선
Quic을 이용한 네트워크 성능 개선
 
SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개
SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개
SonarQube와 함께하는 소프트웨어 품질 세미나 - SonarQube 소개
 
"Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ..."Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ...
 
【2000行弱!】x86用自作カーネルの紹介
【2000行弱!】x86用自作カーネルの紹介【2000行弱!】x86用自作カーネルの紹介
【2000行弱!】x86用自作カーネルの紹介
 
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
 
AWS Fargate on EKS 실전 사용하기
AWS Fargate on EKS 실전 사용하기AWS Fargate on EKS 실전 사용하기
AWS Fargate on EKS 실전 사용하기
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
 
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
 

Similar to PyCon Korea 2019 REST API Document Generation

Schema-First API Design
Schema-First API DesignSchema-First API Design
Schema-First API DesignYos Riady
 
Dead Simple APIs with OpenAPI
Dead Simple APIs with OpenAPIDead Simple APIs with OpenAPI
Dead Simple APIs with OpenAPIChris Tankersley
 
Zen and the Art of REST API documentation - MuCon London 2015
Zen and the Art of REST API documentation - MuCon London 2015Zen and the Art of REST API documentation - MuCon London 2015
Zen and the Art of REST API documentation - MuCon London 2015Steve Judd
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreStormpath
 
Extensible web #html5j
Extensible web #html5jExtensible web #html5j
Extensible web #html5jJxck Jxck
 
PHP. Trends, implementations, frameworks and solutions
PHP. Trends, implementations, frameworks and solutionsPHP. Trends, implementations, frameworks and solutions
PHP. Trends, implementations, frameworks and solutionsOleg Zinchenko
 
Kubernetes API code-base tour
Kubernetes API code-base tourKubernetes API code-base tour
Kubernetes API code-base tourStefan Schimanski
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Max Lai
 
Introduction to CloudStack API
Introduction to CloudStack APIIntroduction to CloudStack API
Introduction to CloudStack APIKrunal Jain
 
API Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIsAPI Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIsTom Johnson
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays
 
SPARQLing Services
SPARQLing ServicesSPARQLing Services
SPARQLing ServicesLeigh Dodds
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009sullis
 
Services web RESTful
Services web RESTfulServices web RESTful
Services web RESTfulgoldoraf
 

Similar to PyCon Korea 2019 REST API Document Generation (20)

Gohan
GohanGohan
Gohan
 
Schema-First API Design
Schema-First API DesignSchema-First API Design
Schema-First API Design
 
Dead Simple APIs with OpenAPI
Dead Simple APIs with OpenAPIDead Simple APIs with OpenAPI
Dead Simple APIs with OpenAPI
 
Zen and the Art of REST API documentation - MuCon London 2015
Zen and the Art of REST API documentation - MuCon London 2015Zen and the Art of REST API documentation - MuCon London 2015
Zen and the Art of REST API documentation - MuCon London 2015
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET Core
 
Extensible web #html5j
Extensible web #html5jExtensible web #html5j
Extensible web #html5j
 
PHP. Trends, implementations, frameworks and solutions
PHP. Trends, implementations, frameworks and solutionsPHP. Trends, implementations, frameworks and solutions
PHP. Trends, implementations, frameworks and solutions
 
Kubernetes API code-base tour
Kubernetes API code-base tourKubernetes API code-base tour
Kubernetes API code-base tour
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
Talking to Web Services
Talking to Web ServicesTalking to Web Services
Talking to Web Services
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
 
Introduction to CloudStack API
Introduction to CloudStack APIIntroduction to CloudStack API
Introduction to CloudStack API
 
API Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIsAPI Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIs
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
 
SPARQLing Services
SPARQLing ServicesSPARQLing Services
SPARQLing Services
 
Rest api-basic
Rest api-basicRest api-basic
Rest api-basic
 
Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009Web Services and Android - OSSPAC 2009
Web Services and Android - OSSPAC 2009
 
Services web RESTful
Services web RESTfulServices web RESTful
Services web RESTful
 

Recently uploaded

Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
chpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMM
chpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMMchpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMM
chpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMMNanaAgyeman13
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
GSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptx
GSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptxGSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptx
GSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptxshuklamittt0077
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfDrew Moseley
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
ROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.ppt
ROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.pptROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.ppt
ROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.pptJohnWilliam111370
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfisabel213075
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfNainaShrivastava14
 

Recently uploaded (20)

Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
chpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMM
chpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMMchpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMM
chpater16.pptxMMMMMMMMMMMMMMMMMMMMMMMMMMM
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
GSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptx
GSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptxGSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptx
GSK & SEAMANSHIP-IV LIFE SAVING APPLIANCES .pptx
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
ROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.ppt
ROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.pptROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.ppt
ROBOETHICS-CCS345 ETHICS AND ARTIFICIAL INTELLIGENCE.ppt
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdf
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
 

PyCon Korea 2019 REST API Document Generation

  • 2. 5 Python backend app Flask 2 Django
  • 3. ●REST API ●OpenAPI Specification ●Python Web Applications & OpenAPI Specification ●Django API ●Flask API
  • 5. REST API ? HTTP METHODS https://api.example.com/speakers https://api.example.com/speakers/1 GET 1 POST - PUT request body request body field null 1 request body request body field null PATCH request body request body field 1 request body request body field DELETE 1 OpenAPI Specification Python Web Apps & OAS Django FlaskREST API Representational State Transfer
  • 6. ( API ) REST API OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
  • 7. ●API , ●Host, port ● ●URI ●URI HTTP method ● request header, body ● response status code, body REST API OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
  • 8. REST API OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
  • 9. ..
 ● .. ● ● REST API OpenAPI Specification Python Web Apps & OAS Django FlaskREST API
  • 11. RESTful API JSON, YAML API , / 
 Swagger OpenAPI Initiative OpenAPI Specification https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 12. API toolset ●Swagger Codegen ●Swagger Editor ●Swagger UI Swagger UI ●OpenAPI JSON/YAML 
 API Swagger? https://petstore.swagger.io/ REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 13. API toolset ●Swagger Codegen ●Swagger Editor ●Swagger UI Swagger UI ●OpenAPI JSON/YAML 
 API Swagger? https://petstore.swagger.io/ REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 14. API toolset ●Swagger Codegen ●Swagger Editor ●Swagger UI Swagger UI ●OpenAPI JSON/YAML 
 API Swagger? https://petstore.swagger.io/ REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 15. API toolset ●Swagger Codegen ●Swagger Editor ●Swagger UI Swagger UI ●OpenAPI JSON/YAML 
 API Swagger? https://petstore.swagger.io/ REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 16. API toolset ●Swagger Codegen ●Swagger Editor ●Swagger UI Swagger UI ●OpenAPI JSON/YAML 
 API Swagger? REST API Python Web Apps & OAS Django FlaskOpenAPI Specification https://petstore.swagger.io/
  • 17. title: Sample PyCON speaker API description: This is a sample server for a PyCON speaker management. termsOfService: http://example.com/terms/ contact: name: API Support url: http://www.example.com/support email: support@example.com license: name: MIT version: 1.0.1 OpenAPI Specification YAML https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 18. servers: - url: https://pycon-speaker.com:{port}/{basePath} description: The production API server variables: port: enum: - '443' - '8443' default: '8443' description: 8443 is for demo. basePath: default: v2 OpenAPI Specification YAML https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 19. paths: /speakers: get: description: Returns all speakers from the system that the user has access to responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker' OpenAPI Specification YAML https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 20. components: schemas: Speaker: required: - id - email properties: id: type: integer format: int64 email: type: string name: type: string OpenAPI Specification YAML https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md REST API Python Web Apps & OAS Django FlaskOpenAPI Specification
  • 21. OpenAPI Specification YAML https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md REST API Python Web Apps & OAS Django FlaskOpenAPI Specification OpenAPI Specification
 JSON / YAML APISwagger UI paths: /speakers: get: description: Returns all speakers from the system that the user has access to responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker'
  • 22. Python Web Application & 
 OpenAPI Specification
  • 23. Generating OpenAPI YAML Web Application Server ●Server information ○Base URL, port, ... ●Routing information ○ path ●Request params ●Response schema REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 24. Generating OpenAPI YAML servers: - url: https://pycon-speaker.com:{port}/{basePath} description: The production API server variables: port: enum: - '443' - '8443' default: '8443' description: 8443 is for demo. basePath: default: v2 Web Application Server ●Server information ○Routing information ■ Request params ■ Response schema REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 25. Generating OpenAPI YAML paths: /speakers: get: description: Returns all speakers responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker' Web Application Server ●Server information ○Routing information ■ Request params ■ Response schema REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 26. Generating OpenAPI YAML paths: /speakers: get: description: Returns all speakers responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker' Web Application Server ●Server information ○Routing information ■ Request params ■ Response schema REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 27. Generating OpenAPI YAML paths: /speakers: get: description: Returns all speakers responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker' Web Application Server ●Server information ○Routing information ■ Request params ■ Response schema REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 28. Django & OAS Django Server ●Server information → ○Routing information → urls.urlpatterns ■ Request params → View, Model ■ Response schema → View, Model REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 29. Django & OAS Server Information ● , Routing Information ●urlpatterns # urls.py openapi_schema_view = get_schema_view( openapi.Info( title='Demo API', default_version='v1', ), url='https://demo.example.com:3000', public=True, ) urlpatterns = [ path('admin/', admin.site.urls), path('docs/', openapi_schema_view.with_ui(...), path('', include(router.urls)), ] REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 30. Django & OAS Request Params, Response Schema ●Function Based View ○ view request, response ■ docstring ?
 → API def speakers_list(request): """ response - type: list - content - name: , string - email: , string - organization: , object - name: , string """ ... return speakers REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 31. django/views/generics/edit.py Django & OAS Request Params, Response Schema ●Class Based View ○django/views/generics ○cls.model model 
 → response schema ○cls.get_form_class() form 
 → request parameters CreateView ModelFormMixin get_form_class() SingleObjectMixin model REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 32. Flask & OAS Flask Server ●Server information → ○Routing information → Flask.view_functions ■ Request params → View?, Model? ■ Response schema → View?, Model? REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 33. Flask & OAS Routing Information ●Flask.view_functions # flask/app.py: Flask def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator def add_url_rule(self, rule, endpoint, view_func, ...): … self.view_functions[endpoint] = view_func … REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 34. Flask & OAS Request Params, Response Schema ●Function View (Django ) ○ view request, response ■ docstring ? → API ●Pluggable View(Class Based View) ○Function View Extension REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 35. ●Server information ○ ●Routing information ○ framework routing ●Request params ○(Django) View class form ●Response schema ○(Django) View class model REST API OpenAPI Specification Django FlaskPython Web Apps & OAS
  • 37. ●APIView (Django view wrapping) ●ModelViewSet (generic views) ○Serializer ○Filterset ○Permission ●OpenAPI schema ( ) Django REST Framework REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 38. ●APIView (Django view wrapping) ●ModelViewSet (generic views) ○Serializer ○Filterset ○Permission ●OpenAPI schema ( ) Django REST Framework REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango >>> speaker <Speaker: Speaker object (1)> >>> serializer = SpeakerSerializer(speaker) >>> serializer.data {'email': 'test@pycon.kr', 'name': 'test', 'created': '2019-08-18T12:15:10.375877'}
  • 39. ●APIView (Django view wrapping) ●ModelViewSet (generic views) ○Serializer ○Filterset ○Permission ●OpenAPI schema ( ) Django REST Framework REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango >>> data = {'email': 'another@pycon.kr', 'name': 'another test', 'created': '2019-08-18T12:16:10.375877'} >>> serializer = SpeakerSerializer(data=data) >>> serializer.is_valid() True >>> serializer.validated_data {'email': 'another@pycon.kr', 'name': 'another test', 'created': datetime.datetime(2019, 08, 18, 12, 16, 10, 375877)}
  • 40. ●APIView (Django view wrapping) ●ModelViewSet (generic views) ○Serializer ○Filterset ○Permission ●OpenAPI schema ( ) Django REST Framework REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango >>> serializer.save() <Speaker: Speaker object (2)>
  • 41. ●APIView (Django view wrapping) ●ModelViewSet (generic views) ○Serializer ○Filterset ○Permission ●OpenAPI schema ( ) Django REST Framework REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 42. API ●Django REST Swagger ○ https://github.com/marcgibbons/django-rest-swagger
 ●DRF Yet another Swagger generator ○ https://github.com/axnsan12/drf-yasg ○ swagger/redoc UI Django REST Framework https://www.django-rest-framework.org/topics/documenting-your-api/ REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 43. API ●Django REST Swagger ○ https://github.com/marcgibbons/django-rest-swagger ○ 2019-06-04 Deprecated…
 ●DRF Yet another Swagger generator ○ https://github.com/axnsan12/drf-yasg ○ swagger/redoc UI ○ Django REST Framework https://www.django-rest-framework.org/topics/documenting-your-api/ REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 44. ●View serializer request / response schema ● override decorator ●OpenAPI Spec 2.0 schema ○DRF OpenAPI schema DRF-YASG REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 45. DRF native vs DRF-YASG # Django REST Framework (X) responses: '200': content: application/json: schema: properties: id: type: integer readOnly: true date: type: string format: date packages: type: array items: type: string # DRF-YASG (O) responses: '200': schema: type: object properties: count: type: integer next: type: string format: uri previous: type: string format: uri results: type: array items: $ref: '#/definitions/Record' REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 46. DRF native vs DRF-YASG # Django REST Framework (X) responses: '200': content: application/json: schema: properties: id: type: integer readOnly: true date: type: string format: date packages: type: array items: type: string # DRF-YASG (O) responses: '200': schema: type: object properties: count: type: integer next: type: string format: uri previous: type: string format: uri results: type: array items: $ref: '#/definitions/Record' REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 47. DRF-YASG REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango urlpatterns (url → view class mappings) /speakers → SpeakerViewSet serializer class = SpeakerSerializer /organizations → OrganizationViewSet serializer class = OrganizationSerializer
  • 48. DRF-YASG REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango urlpatterns SpeakerViewSet serializer class Speaker (id, name, email, organization_id) SpeakerSerializer model = Speaker id: int name: str email: str organization_id: int, read-only organization: OrganizationSerializer, write-only
  • 49. DRF-YASG REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango urlpatterns SpeakerViewSet serializer class SpeakerSerializer model = Speaker id: int name: str email: str organization_id: int, read-only organization: OrganizationSerializer, write-only OrganizationSerializer model = Organization id: int name: str
  • 50. DRF-YASG # drf_yasg/views.py class SchemaView(APIView): ... def get(self, request, version='', format=None): ... schema = generator.get_schema(request, self.public) ... return Response(schema) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 51. DRF-YASG # drf_yasg/generators.py class OpenAPISchemaGenerator: def get_schema(self, request=None, public=False): ... paths, prefix = self.get_paths(endpoints, ...) ... return openapi.Swagger( paths=paths, ... ) def get_paths(self, endpoints, ...): ... for url, (..., methods) in sorted(endpoints.items()): ... for method, view in methods: ... operation = self.get_operation(url, method, ...) ... ... def get_operation(self, url, method, ...): ... operation = view_inspector.get_operation(...) ... urls.urlpatterns REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 52. DRF-YASG # drf_yasg/generators.py class OpenAPISchemaGenerator: def get_schema(self, request=None, public=False): ... paths, prefix = self.get_paths(endpoints, ...) ... return openapi.Swagger( paths=paths, ... ) def get_paths(self, endpoints, ...): ... for path, (..., methods) in sorted(endpoints.items()): ... for method, view in methods: ... operation = self.get_operation(path, method, ...) ... ... def get_operation(self, path, method, ...): ... operation = view_inspector.get_operation(...) ... REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango paths: /speakers: get: description: Returns all speakers responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker' urls.urlpatterns
  • 53. DRF-YASG # drf_yasg/generators.py class OpenAPISchemaGenerator: def get_schema(self, request=None, public=False): ... paths, prefix = self.get_paths(endpoints, ...) ... return openapi.Swagger( paths=paths, ... ) def get_paths(self, endpoints, ...): ... for url, (..., methods) in sorted(endpoints.items()): ... for method, view in methods: ... operation = self.get_operation(url, method, ...) ... ... def get_operation(self, url, method, ...): ... operation = view_inspector.get_operation(...) ... REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 54. DRF-YASG # drf_yasg/generators.py class OpenAPISchemaGenerator: def get_schema(self, request=None, public=False): ... paths, prefix = self.get_paths(endpoints, ...) ... return openapi.Swagger( paths=paths, ... ) def get_paths(self, endpoints, ...): ... for path, (..., methods) in sorted(endpoints.items()): ... for method, view in methods: ... operation = self.get_operation(path, method, ...) ... ... def get_operation(self, path, method, ...): ... operation = view_inspector.get_operation(...) ... REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango paths: /speakers: get: description: Returns all speakers responses: '200': description: A list of speakers. content: application/json: schema: type: array items: $ref: '#/components/schemas/Speaker'
  • 55. DRF-YASG # drf_yasg/generators.py class OpenAPISchemaGenerator: def get_schema(self, request=None, public=False): ... paths, prefix = self.get_paths(endpoints, ...) ... return openapi.Swagger( paths=paths, ... ) def get_paths(self, endpoints, ...): ... for path, (..., methods) in sorted(endpoints.items()): ... for method, view in methods: ... operation = self.get_operation(path, method, ...) ... ... def get_operation(self, path, method, ...): ... operation = view_inspector.get_operation(...) ... REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 56. DRF-YASG # drf_yasg/inspectors/view.py class SwaggerAutoSchema(ViewInspector): def get_operation(self, operation_keys=None): ... parameters = body + query parameters = filter_none(parameters) parameters = self.add_manual_parameters(parameters) ... responses = self.get_responses() return openapi.Operation( parameters=parameters, responses=responses, ... ) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 57. DRF-YASG # drf_yasg/inspectors/view.py class SwaggerAutoSchema(ViewInspector): def get_operation(self, operation_keys=None): ... parameters = body + query parameters = filter_none(parameters) parameters = self.add_manual_parameters(parameters) ... responses = self.get_responses() return openapi.Operation( parameters=parameters, responses=responses, ... ) 1. self.view serializer 2. field inspector field ○ Nested serializer ○ SerializerMethodField ○ Paginated response 3. openapi Response REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 58. DRF-YASG ●urlpatterns endpoints(url → view mapping) 
 ●endpoints iterate url, method request response 
 ●request response field inspector 
 Nested serializer 
 ● request response OpenAPI schema REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 59. DRF-YASG # main/urls.py ... openapi_schema_view = get_schema_view( openapi.Info( title='Demo API', default_version='v1', ), public=True, ) urlpatterns = [ path('admin/', admin.site.urls), path('docs/', openapi_schema_view.with_ui('redoc')), path('', include(router.urls)), ] REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 60. DRF-YASG # main/models.py class Speaker(models.Model): id = AutoField(primary_key=True) email = EmailField() name = CharField(max_length=10, blank=True) organization = ForeignKey( Organization, null=True, on_delete=models.SET_NULL, related_name='speakers' ) # main/views.py class SpeakerViewSet(ModelViewSet): queryset = Speaker.objects.all() serializer_class = SpeakerSerializer REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 61. DRF-YASG # main/serializers.py class OrganizationSerializer(ModelSerializer): ... class SpeakerSerializer(ModelSerializer): organization = OrganizationSerializer(read_only=True, help_text='Read-only ') organization_id = PrimaryKeyRelatedField(source='organization', queryset=Organization.objects.all(), write_only=True, help_text='Write-only ') class Meta: model = Speaker fields = '__all__' write_only_fields = ('organization_id',) read_only_fields = ('organization',) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 62. DRF-YASG # main/serializers.py class OrganizationSerializer(ModelSerializer): ... class SpeakerSerializer(ModelSerializer): organization = OrganizationSerializer(read_only=True, help_text='Read-only ') organization_id = PrimaryKeyRelatedField(source='organization', queryset=Organization.objects.all(), write_only=True, help_text='Write-only ') class Meta: model = Speaker fields = '__all__' write_only_fields = ('organization_id',) read_only_fields = ('organization',) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango $ curl -X POST localhost:8000/speakers -d "name=test&email=test@pycon.kr&organization_id=1" { "id": 1, "name": "test", "email": "test@pycon.kr", "organization": { "id": 1, "name": "test organization" } }
  • 63. DRF-YASG REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 64. DRF-YASG REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 65. DRF-YASG Custom Action # main/views.py class SpeakerViewSet(ModelViewSet): queryset = Speaker.objects.all() serializer_class = SpeakerSerializer @action(methods=['get'], detail=False) def count(self, _): return Response({'result': Speaker.objects.count()}) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 66. DRF-YASG Custom Action Response schema 
 ! REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 67. DRF-YASG Custom Action # main/views.py class SpeakerViewSet(ModelViewSet): queryset = Speaker.objects serializer_class = SpeakerSerializer @swagger_auto_schema( operation_description=' API', responses={ '200': openapi.Response( description='', schema=openapi.Schema( type='object', properties={'result': openapi.Schema(type='integer')} ) ) } ) @action(methods=['get'], detail=False) def count(self, _): return Response({'result': Speaker.objects.count()}) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 68. DRF-YASG Custom Action # main/views.py class SpeakerCountSerializer(Serializer): result = IntegerField() class SpeakerViewSet(ModelViewSet): queryset = Speaker.objects serializer_class = SpeakerSerializer @swagger_auto_schema( operation_description=' API', responses={'200': SpeakerCountSerializer} ) @action(methods=['get'], detail=False) def count(self, _): return Response({'result': Speaker.objects.count()}) REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 69. DRF-YASG Custom Action REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 70. DRF-YASG ● ○read_only, write_only ○serializer ●Redoc UI request ●Swagger UI ●OpenAPI Spec 2.0 REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 71. DRF-YASG ● ○read_only, write_only ○serializer ●Redoc UI request ●Swagger UI ●OpenAPI Spec 2.0 REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango
  • 72. DRF-YASG ● ○read_only, write_only ○serializer ●Redoc UI request ●Swagger UI ●OpenAPI Spec 2.0 REST API OpenAPI Specification Python Web Apps & OAS FlaskDjango https://swagger.io/blog/news/whats-new-in-openapi-3-0/
  • 74. ●Resource View get, post 
 ●arg parser View 
 ●field model marshal Flask-RESTful REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 75. ●Flask-RESTful ○ Flask-RESTful API ● API ●Flask-RESTful Flask-RESTPlus REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 76. ●Flask RESTful Swagger 2.0 ○ OpenAPI Spec 1.2 ○ 2.0 ●SQLAlchemy Flask RESTful Swagger (SAFRS) ○ DB model class ○ Model method docstring API REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 77. Flask-RESTPlus REST API OpenAPI Specification Python Web Apps & OAS Django Flask ●Flask RESTful Swagger 2.0 ○ OpenAPI Spec 1.2 ○ 2.0 ●SQLAlchemy Flask RESTful Swagger (SAFRS) ○ DB model class ○ Model method docstring
  • 78. Flask-RESTPlus REST API OpenAPI Specification Python Web Apps & OAS Django Flask ●Flask RESTful Swagger 2.0 ○ OpenAPI Spec 1.2 ○ 2.0 ●SQLAlchemy Flask RESTful Swagger (SAFRS) ○ DB model class ○ Model method docstring 
 ●Flask-RESTPlus 

  • 79. Flask-RESTPlus from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_restplus import Api app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) api = Api(app) REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 80. Flask-RESTPlus class OrganizationModel(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), nullable=False) class SpeakerModel(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(10), nullable=True) email = db.Column(db.String(120), unique=True, nullable=False) organization_id = db.Column(db.Integer, db.ForeignKey('organization_model.id')) organization = relationship('OrganizationModel') REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 81. Flask-RESTPlus organization_output = api.model('OrganizationOutput', { 'name': fields.String }) speaker_output = api.model('SpeakerOutput', { 'name': fields.String, 'email': fields.String, 'organization': fields.Nested(organization_output) }) speaker_input = reqparse.RequestParser() speaker_input.add_argument('email', type=str) speaker_input.add_argument('name', type=str) speaker_input.add_argument('organization_id', type=int) REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 82. Flask-RESTPlus @api.route('/speakers') class Speaker(Resource): @api.marshal_list_with(speaker_output) def get(self): return Speaker.query.all() @api.expect(speaker_input) @api.marshal_with(speaker_output) def post(self): args = speaker_input.parse_args() speaker = SpeakerModel(**args) db.session.add(speaker) db.session.commit() return speaker $ curl -X POST localhost:5000/speakers -d "name=test&email=test@pycon.kr&organization_id=1" { "name": "test", "email": "test@pycon.kr", "organization": { "name": "test organization" } } REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 83. Flask-RESTPlus REST API OpenAPI Specification Python Web Apps & OAS Django Flask
  • 84.
  • 85. ●Web framework → OpenAPI YAML / JSON → Swagger / Redoc UI ● web framework(Bottle, Sanic, Vibora ) 
 runtime routing (path → view function) ○ OpenAPI schema ○ Sanic-RESTPlus ●drf-yasg, Flask-RESTPlus
  • 86. www.aitrics.com contact@aitrics.com Yongseon Lee <yongseon@aitrics.com> ● REST API (Yongseon Lee) 
 18th (Sun) 11:55 ~ 12:35 ● Advanced Python testing techniques (Jaeman An)
 18th (Sun) 11:55 ~ 12:35 ● Django Query Optimization (Soyoung Yoon)
 18th (Sun) 13:55 ~ 14:35 ● Pickle & Custom Binary Serializer (Young Seok Kim)
 18th (Sun) 14:55 ~ 15:35 Talks from AITRICS