Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1021ky/5cbc576dd03daee697619c8240050d9e to your computer and use it in GitHub Desktop.
Save 1021ky/5cbc576dd03daee697619c8240050d9e to your computer and use it in GitHub Desktop.
openBD APIの仕様をOpenAPIで書いたもの
openapi: 3.0.0
info:
title: openBD API
description: "[openBDプロジェクト(カーリル・版元ドットコム)](https://openbd.jp)によって提供される書誌情報・書影を、だれでも自由に使える、高速なAPI."
version: 1.0.0
servers:
- url: "https://api.openbd.jp/v1"
description: server url
host: "https://api.openbd.jp/"
basePath: "v1"
tags:
- name: "default"
description: "ドキュメントルート"
paths:
/get:
parameters:
- in: query
name: isbn
required: true
schema:
type: array
items:
type: string
format: isbn
description: ISBNを指定。複数指定の場合はカンマ[,]で区切る。ISBNをXXX-X-XXXX-XXXX-Xの形式で指定する。1,000件まで複数指定。
- in: query
name: pretty
schema:
type: boolean
allowEmptyValue: true
description: 指定された場合、JSONを整形表示する。
get:
summary: Returns book info summry
description: 書誌の概要を取得する。
responses:
'200':
description: A JSON object of book summary
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/BookInfo'
post:
summary: Returns book info summry
description: 書誌の概要を取得する。
parameters:
- in: query
name: isbn
required: true
schema:
type: array
items:
type: string
format: isbn
description: ISBNを指定。複数指定の場合はカンマ[,]で区切る。ISBNをXXX-X-XXXX-XXXX-Xの形式で指定する。1,0000件まで複数指定。
responses:
'200':
description: A JSON object of book summary
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/BookInfo'
components:
schemas:
BookInfo:
type: object
additionalProperties: false
properties:
onix:
type: object
additionalProperties: false
properties:
ProductIdentifier:
description: 識別情報(ISBN)
type: object
additionalProperties: false
# additionalProperties: false
properties:
ProductIDType:
description: 'IDの種類[ISBN固定]'
type: string
pattern: ^15$
IDValue:
description: ISBN(13桁)
type: string
pattern: '([0-9]+)'
RecordReference:
description: ISBN(13桁)
type: string
PublishingDetail:
description: 出版社に関する情報
type: object
additionalProperties: false
# additionalProperties: false
properties:
PublishingDate:
description: 商品の出版に関する日付情報
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
PublishingDateRole:
description: 発売日の種類
type: string
pattern: '^([0-9]{2})$'
Date:
description: 発売日
type: string
Imprint:
description: 「発行元出版社」に関する情報
type: object
additionalProperties: false
# additionalProperties: false
properties:
ImprintName:
description: 「発行元出版社」名
type: string
ImprintIdentifier:
description: 「発行元出版社」コード
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
IDValue:
description: ID
type: string
ImprintIDType:
description: IDタイプ
type: string
Publisher:
description: 「発行元出版社」と異なる場合、「発売元出版社」についての情報
type: object
additionalProperties: false
# additionalProperties: false
properties:
PublishingRole:
description: Publisher 【出版社】 に固定
type: string
PublisherName:
description: 「発売元出版社」名
type: string
PublisherIdentifier:
description: 「発売元出版社」コード
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
IDValue:
description: ID
type: string
PublisherIDType:
description: IDタイプ
type: string
NotificationType:
description: 削除フラグ
type: string
pattern: ^03$|^02$
ProductSupply:
description: 市場における商品の出版状況、供給等
type: object
additionalProperties: false
# additionalProperties: false
properties:
SupplyDetail:
description: 商品のアベイラビリテイ(入手可能性)や価格、その他の供給状況
type: object
additionalProperties: false
# additionalProperties: false
properties:
ReturnsConditions:
description: 返品条件について
type: object
additionalProperties: false
# additionalProperties: false
properties:
ReturnsCodeType:
description: 「ONIX返品条件コード」 に固定
type: string
ReturnsCode:
description: 条件コード
type: string
ProductAvailability:
description: 「近刊情報センター」では、99に固定
type: string
pattern: ^99$
Price:
description: 価格(単価)について
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
PriceType:
description: 価格タイプ
type: string
PriceAmount:
description: 価格
type: string
CurrencyCode:
description: 通貨
type: string
PriceDate:
description: 特価期限
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
PriceDateRole:
description: 価格の種類
type: string
Date:
description: 日付
type: string
Price:
description: 価格
type: string
DescriptiveDetail:
description: 商品に関する情報
type: object
additionalProperties: false
# additionalProperties: false
properties:
Language:
description: 表記に利用する言語
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
LanguageCode:
description: 価格の種類
type: string
LanguageRole:
description: 言語コード
type: string
pattern: ^01$
CountryCode:
description: 国コード
type: string
TitleDetail:
description: 商品の「書名」を設定
type: object
additionalProperties: false
# additionalProperties: false
properties:
TitleType:
description: 'タイトルの種類[01に固定]'
type: string
pattern: ^01$
TitleElement:
description: タイトルの要素
type: object
additionalProperties: false
# additionalProperties: false
properties:
TitleElementLevel:
description: 'タイトルのレベル[01に固定]'
type: string
pattern: ^01$
TitleText:
description: 書名
type: object
additionalProperties: false
# additionalProperties: false
properties:
collationkey:
description: 読み仮名
type: string
content:
description: 書名
type: string
Subtitle:
description: サブタイトル
type: object
additionalProperties: false
# additionalProperties: false
properties:
collationkey:
description: 読み仮名
type: string
content:
description: 書名
type: string
ProductForm:
description: 判型
type: string
ProductFormDetail:
description: 判型の詳細コード
type: string
Collection:
description: シリーズに関する情報
type: object
additionalProperties: false
# additionalProperties: false
properties:
CollectionType:
description: '種類コード[10に固定]'
type: string
pattern: ^10$
CollectionSequence:
description: 「配本回数」について
type: object
additionalProperties: false
# additionalProperties: false
properties:
CollectionSequenceType:
description: '配本回数コード[03に固定]'
type: string
pattern: ^03$
CollectionSequenceNumber:
description: 配本回数
type: string
TitleDetail:
description: シリーズタイトル
type: object
additionalProperties: false
# additionalProperties: false
properties:
TitleType:
description: 'タイトルの種類[01に固定]'
type: string
pattern: ^01$
TitleElement:
description: シリーズ・レーベルの名前
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
TitleElementLevel:
description: シリーズの種類
type: string
pattern: ^02$|^03$
TitleText:
description: シリーズ名
type: object
additionalProperties: false
# additionalProperties: false
properties:
collationkey:
description: 読み仮名
type: string
content:
description: タイトル
type: string
PartNumber:
description: シリーズの巻次
type: string
Extent:
description: 商品に関連する(数値的)範囲、程度など
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
ExtentType:
description: '数値の種類[11はページ数]'
type: string
pattern: '^11$'
ExtentUnit:
description: '単位[03ページに固定]'
type: string
pattern: '^03$'
ExtentValue:
description:
type: string
Measure:
description: タテ・ヨコの実寸
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
MeasureType:
description: '数値の種類[01縦/02横]'
type: string
pattern: '^01$|^02$'
MeasureUnitCode:
description: '単位[mmに固定]'
type: string
pattern: '^mm$'
Measurement:
description:
type: string
Contributor:
description: 商品の著者情報
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
ContributorRole:
description: 著者区分
type: array
items:
type: string
SequenceNumber:
description: 表示順序
type: string
PersonName:
description: 著者名
type: object
additionalProperties: false
# additionalProperties: false
properties:
collationkey:
description: 読み仮名
type: string
content:
description: タイトル
type: string
BiographicalNote:
description: 著者略歴
type: string
ProductComposition:
description: セット商品分売可否
type: string
Audience:
description: 商品の対象読者を示す方法
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
AudienceCodeType:
description: 読者コード種類
type: string
AudienceCodeValue:
description: 読者コード
type: string
Subject:
description: 商品の主題、テーマ、カテゴリなど
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
SubjectSchemeIdentifier:
description: カテゴリ
type: string
SubjectCode:
description: 78 or 79の場合に、「Cコード」または「ジャンルコード」
type: string
MainSubject:
description: メーンとなるSubjectのカテゴリ
type: string
SubjectHeadingText:
description: キーワード
type: string
ProductPart:
description: 付録の有無
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
NumberOfItemsOfThisForm:
description: '付録の数量[1に固定]'
type: string
ProductForm:
description: '付録コード[00に固定]'
type: string
ProductFormDescription:
description: 付録の内容
type: string
CollateralDetail:
description: 商品の付帯項目
type: object
additionalProperties: false
# additionalProperties: false
properties:
SupportingResource:
description: ONIXデータを補助する販促情報や追加情報などのデジタルデータ
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
ResourceContentType:
description: '種類[01書影07商品イメージ]'
type: string
pattern: ^01$|^07$
ResourceMode:
description: '[03静止画に固定]'
type: string
ContentAudience:
description: '[01に固定]'
type: string
ResourceVersion:
description: 補助リソースのバージョン
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
ResourceLink:
description: フルURI
type: string
pattern: '^https:\/\/cover.openbd.jp\/'
ResourceForm:
description: '[02に固定]'
type: string
ResourceVersionFeature:
description: ファイル名とファイル形式
type: array
items:
type: object
additionalProperties: false
properties:
ResourceVersionFeatureType:
description: ファイル名
type: string
FeatureValue:
description: ファイル形式
type: string
TextContent:
description: 内容紹介
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
Text:
description: テキスト
type: string
TextType:
description: 種類コード
type: string
pattern: ^02$|^03$|^04$|^23$
ContentAudience:
description: 意図されている読者
type: string
hanmoto:
type: object
additionalProperties: false
description: 版元独自書誌
properties:
datekoukai:
description: 公開日
type: string
format: date-time
datemodified:
description: 最終更新日
type: string
format: date-time
datecreated:
description: 最終作成日
type: string
format: date-time
dateshuppan:
description: 出版日
type: string
dokushakakikomipagesuu:
description: 読者書き込みページ数
type: integer
kubunhanbai:
description: 販売区分
type: boolean
toji:
description: 本の綴じ方
type: string
zaiko:
description: 在庫ステータス
type: integer
han:
description:
type: string
genrecodetrc:
description: TRC用ジャンルコード
type: integer
genrecodetrcjidou:
description: TRC用児童ジャンルコード
type: integer
bikoutrc:
description: TRC用備考
type: string
ndccode:
description: NDC(日本十進分類法)
type: string
kaisetsu105w:
description: 105文字程度の解説
type: string
hanmotokarahitokoto:
description: 版元からひとこと
type: string
kankoukeitai:
description: 刊行形態
type: string
lanove:
description: ラノベフラグ
type: boolean
maegakinado:
description: まえがきなど
type: string
hastameshiyomi:
description: 試し読みフラグ
type: boolean
datezeppan:
description: 絶版日
type: string
jushoujouhou:
description: 受賞情報
type: string
datejuuhanyotei:
description: 重版予定日
type: string
genshomei:
description: 原書名
type: string
kanrensho:
description: 関連書
type: string
tsuiki:
description: 追記
type: string
obinaiyou:
description: 帯の内容
type: string
rubynoumu:
description: ルビの有無
type: boolean
furokusonota:
description: 付録その他
type: string
furoku:
description: 付録コード
type: integer
zasshicode:
description: 雑誌コード
type: string
ruishokyougousho:
description: 類書・競合書
type: string
sonotatokkijikou:
description: その他の特記事項
type: string
gatsugougousuu:
description: 月号・号数
type: string
dokushakakikomi:
description: 読者書き込み
type: string
kanrenshoisbn:
description: 関連書ISBN
type: string
bessoushiryou:
description: 別称資料?
type: string
jyuhan:
description: 重版情報
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
date:
description: 重版日
type: string
format: date-time
ctime:
description: 更新日時
type: string
format: date-time
suri:
description: 刷数
type: integer
comment:
description: コメント
type: string
required:
- date
author:
description: 著者補足情報
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
dokujikubun:
description: 独自区分
type: string
listseq:
description: リストの番号
type: integer
required:
- dokujikubun
- listseq
reviews:
description: 書評情報
type: array
items:
type: object
additionalProperties: false
# additionalProperties: false
properties:
han:
description:
type: string
appearance:
description: 書評掲載日
type: string
post_user:
description: 投稿ユーザー
type: string
kubun_id:
description: 区分ID
type: integer
source:
description: 情報源
type: string
choyukan:
description: 朝刊・夕刊
type: string
source_id:
description: 情報源ID
type: integer
reviewer:
description: 評者
type: string
gou:
description:
type: string
link:
description: リンク
type: string
format: url
hanmotoinfo:
description: 版元情報
type: object
additionalProperties: false
# additionalProperties: false
properties:
name:
description: 名前
type: string
yomi:
description: よみ
type: string
url:
description: URL
type: string
twitter:
description: Twitterアドレス
type: string
facebook:
description: Facebookアドレス
type: string
hatsubai:
description: 発売元
type: string
hatsubaiyomi:
description: 発売元よみ
type: string
required:
- datemodified
# additionalProperties: false
summary:
description: 書誌の概要
type: object
additionalProperties: false
# additionalProperties: false
properties:
isbn:
description: ISBN
type: string
title:
description: 書名
type: string
volume:
description: 巻号
type: string
series:
description: シリーズ名
type: string
author:
description: 著者名
type: string
publisher:
description: 出版者
type: string
pubdate:
description: 出版年月
type: string
cover:
description: 書影URL
type: string
required:
- isbn
- title
- volume
- series
- author
- publisher
- pubdate
- cover
# coding: utf-8
"""
openBD API
[openBDプロジェクト(カーリル・版元ドットコム)](https://openbd.jp)によって提供される書誌情報・書影を、だれでも自由に使える、高速なAPI. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import datetime
import json
import mimetypes
from multiprocessing.pool import ThreadPool
import os
import re
import tempfile
# python 2 and python 3 compatibility library
import six
from six.moves.urllib.parse import quote
from swagger_client.configuration import Configuration
import swagger_client.models
from swagger_client import rest
class ApiClient(object):
"""Generic API client for Swagger client library builds.
Swagger generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the Swagger
templates.
NOTE: This class is auto generated by the swagger code generator program.
Ref: https://github.com/swagger-api/swagger-codegen
Do not edit the class manually.
:param configuration: .Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
"""
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int if six.PY3 else long, # noqa: F821
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'object': object,
}
def __init__(self, configuration=None, header_name=None, header_value=None,
cookie=None):
if configuration is None:
configuration = Configuration()
self.configuration = configuration
self.pool = ThreadPool()
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = {}
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = 'Swagger-Codegen/1.0.0/python'
def __del__(self):
self.pool.close()
self.pool.join()
@property
def user_agent(self):
"""User agent for this API client"""
return self.default_headers['User-Agent']
@user_agent.setter
def user_agent(self, value):
self.default_headers['User-Agent'] = value
def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value
def __call_api(
self, resource_path, method, path_params=None,
query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
config = self.configuration
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params['Cookie'] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(self.parameters_to_tuples(header_params,
collection_formats))
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
path_params = self.parameters_to_tuples(path_params,
collection_formats)
for k, v in path_params:
# specified safe chars, encode everything
resource_path = resource_path.replace(
'{%s}' % k,
quote(str(v), safe=config.safe_chars_for_path_param)
)
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
query_params = self.parameters_to_tuples(query_params,
collection_formats)
# post parameters
if post_params or files:
post_params = self.prepare_post_parameters(post_params, files)
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(post_params,
collection_formats)
# auth setting
self.update_params_for_auth(header_params, query_params, auth_settings)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
url = self.configuration.host + resource_path
# perform request and return response
response_data = self.request(
method, url, query_params=query_params, headers=header_params,
post_params=post_params, body=body,
_preload_content=_preload_content,
_request_timeout=_request_timeout)
self.last_response = response_data
return_data = response_data
if _preload_content:
# deserialize response data
if response_type:
return_data = self.deserialize(response_data, response_type)
else:
return_data = None
if _return_http_data_only:
return (return_data)
else:
return (return_data, response_data.status,
response_data.getheaders())
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
if obj is None:
return None
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj)
for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `swagger_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
for attr, _ in six.iteritems(obj.swagger_types)
if getattr(obj, attr) is not None}
return {key: self.sanitize_for_serialization(val)
for key, val in six.iteritems(obj_dict)}
def deserialize(self, response, response_type):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialized object, or string of class name.
:return: deserialized object.
"""
# handle file downloading
# save response body into a tmp file and return the instance
if response_type == "file":
return self.__deserialize_file(response)
# fetch data from response object
try:
data = json.loads(response.data)
except ValueError:
data = response.data
return self.__deserialize(data, response_type)
def __deserialize(self, data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if type(klass) == str:
if klass.startswith('list['):
sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('dict('):
sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in six.iteritems(data)}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(swagger_client.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
"""Makes the HTTP request (synchronous) and returns deserialized data.
To make an async request, set the async_req parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return:
If async_req parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter async_req is False or missing,
then the method will return the response directly.
"""
if not async_req:
return self.__call_api(resource_path, method,
path_params, query_params, header_params,
body, post_params, files,
response_type, auth_settings,
_return_http_data_only, collection_formats,
_preload_content, _request_timeout)
else:
thread = self.pool.apply_async(self.__call_api, (resource_path,
method, path_params, query_params,
header_params, body,
post_params, files,
response_type, auth_settings,
_return_http_data_only,
collection_formats,
_preload_content, _request_timeout))
return thread
def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None, _preload_content=True,
_request_timeout=None):
"""Makes the HTTP request using RESTClient."""
if method == "GET":
return self.rest_client.GET(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "HEAD":
return self.rest_client.HEAD(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "OPTIONS":
return self.rest_client.OPTIONS(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "POST":
return self.rest_client.POST(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PUT":
return self.rest_client.PUT(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PATCH":
return self.rest_client.PATCH(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "DELETE":
return self.rest_client.DELETE(url,
query_params=query_params,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
else:
raise ValueError(
"http method must be `GET`, `HEAD`, `OPTIONS`,"
" `POST`, `PATCH`, `PUT` or `DELETE`."
)
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params
def prepare_post_parameters(self, post_params=None, files=None):
"""Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
if post_params:
params = post_params
if files:
for k, v in six.iteritems(files):
if not v:
continue
file_names = v if type(v) is list else [v]
for n in file_names:
with open(n, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
mimetype = (mimetypes.guess_type(filename)[0] or
'application/octet-stream')
params.append(
tuple([k, tuple([filename, filedata, mimetype])]))
return params
def select_header_accept(self, accepts):
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return
accepts = [x.lower() for x in accepts]
if 'application/json' in accepts:
return 'application/json'
else:
return ', '.join(accepts)
def select_header_content_type(self, content_types):
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'application/json'
content_types = [x.lower() for x in content_types]
if 'application/json' in content_types or '*/*' in content_types:
return 'application/json'
else:
return content_types[0]
def update_params_for_auth(self, headers, querys, auth_settings):
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
"""
if not auth_settings:
return
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
if not auth_setting['value']:
continue
elif auth_setting['in'] == 'header':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
querys.append((auth_setting['key'], auth_setting['value']))
else:
raise ValueError(
'Authentication token must be in `query` or `header`'
)
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return six.text_type(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return a original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __hasattr(self, object, name):
return name in object.__class__.__dict__
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
if not klass.swagger_types and not self.__hasattr(klass, 'get_real_child_model'):
return data
kwargs = {}
if klass.swagger_types is not None:
for attr, attr_type in six.iteritems(klass.swagger_types):
if (data is not None and
klass.attribute_map[attr] in data and
isinstance(data, (list, dict))):
value = data[klass.attribute_map[attr]]
kwargs[attr] = self.__deserialize(value, attr_type)
instance = klass(**kwargs)
if (isinstance(instance, dict) and
klass.swagger_types is not None and
isinstance(data, dict)):
for key, value in data.items():
if key not in klass.swagger_types:
instance[key] = value
if self.__hasattr(instance, 'get_real_child_model'):
klass_name = instance.get_real_child_model(data)
if klass_name:
instance = self.__deserialize(data, klass_name)
return instance
from __future__ import print_function
import time
import swagger_client
from swagger_client.configuration import Configuration
from swagger_client.rest import ApiException
from pprint import pprint
config = Configuration()
# config.debug=True
# create an instance of the API class
api_instance = swagger_client.DefaultApi(swagger_client.ApiClient(configuration=config))
isbn = ['978-4-8731-1738-6'] # list[str] | ISBNを指定。複数指定の場合はカンマ[,]で区切る。ISBNをXXX-X-XXXX-XXXX-Xの形式で指定する。1,000件まで複数指定。
pretty = True # bool | 指定された場合、JSONを整形表示する。 (optional)
try:
# Returns book info summry
api_response = api_instance.get_get(isbn, pretty=pretty)
pprint(api_response)
except ApiException as e:
print("Exception when calling DefaultApi->get_get: %s\n" % e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment