How to register Swagger endpoints in Flasgger - flask

Currently using Swagger/Flasgger/Flask to document APIs/routes in an app.
# app.py
from flask import Flask
from flasgger import Swagger
from myapp.blueprints.main import main
app = Flask(__name__)
app.register_blueprint(main)
swag = Swagger(app)
# myapp.blueprints.main.views.py
main = Blueprint('main', __name__)
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', methods=['GET', 'POST'])
def user(user_id=None):
pass
To get documentation on two routes used for the same function, I need to do two things per the Flasgger documentation:
Add a #swag_from declaration pointing to the file that contains the spec.
Give the #main.route and #swag_from the same endpoint kwarg.
When I do step 1, I start seeing the spec information in the Swagger output:
# myapp.blueprints.main.views.py
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', methods=['GET', 'POST'])
#swag_from('user_without_id.yml')
def user(user_id=None):
pass
// > curl localhost:8000/apispec_1.json
{
"definitions": {
"User": {
"properties": {
"age": {
"default": "180",
"description": "The user age (should be integer)",
"type": "integer"
},
"tags": {
"default": [
"wizard",
"hogwarts",
"dead"
],
"description": "optional list of tags",
"items": {
"type": "string"
},
"type": "array"
},
"username": {
"default": "Sirius Black",
"description": "The user name.",
"type": "string"
}
},
"required": [
"username",
"age"
]
}
},
"info": {
"description": "The test-swagger-api spec",
"termsOfService": "/tos",
"title": "test-swagger-api",
"version": "1.0"
},
"paths": {
"/user": {
"get": {
"description": "The default payload is invalid, try it, then change the age to a valid integer and try again<br/>",
"parameters": [
{
"in": "body",
"name": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "Test validation using JsonSchema"
},
"post": {
"description": "The default payload is invalid, try it, then change the age to a valid integer and try again<br/>",
"parameters": [
{
"in": "body",
"name": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "Test validation using JsonSchema"
}
},
"/user/{user_id}": {
"get": {
"description": "The default payload is invalid, try it, then change the age to a valid integer and try again<br/>",
"parameters": [
{
"in": "body",
"name": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "Test validation using JsonSchema"
}
}
},
"swagger": "2.0"
}
However, as soon as I add the endpoint and methods kwargs, my output loses the spec:
# myapp.blueprints.main.views.py
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', endpoint='my-new-endpoint', methods=['GET', 'POST'])
#swag_from('user_without_id.yml', endpoint='my-new-endpoint', methods=['GET', 'POST'])
def user(user_id=None):
pass
// > curl localhost:8000/apispec_1.json
{
"definitions": {},
"info": {
"description": "The test-swagger-api spec",
"termsOfService": "/tos",
"title": "test-swagger-api",
"version": "1.0"
},
"paths": {},
"swagger": "2.0"
}
Not sure where the documentation is going. Flasgger's blueprint example doesn't show how to make this work with multiple routes on a single function.

https://stackoverflow.com/a/55109061/3316036
#swag_from needs to contain the blueprint name in its endpoint field which is unfortunately not clear from the flasgger docs.
# myapp.blueprints.main.views.py
#main.route('/user/<path:user_id>', methods=['GET', 'PUT', 'DELETE'])
#main.route('/user', endpoint='my-new-endpoint', methods=['GET', 'POST'])
#swag_from('user_without_id.yml', endpoint='main.my-new-endpoint', methods=['GET', 'POST'])
def user(user_id=None):
pass

Related

Infinite loading using Authorization header with swagger 2.0

I'm programming a swagger documentation with swagger 2.0 and the request containing an authorization header doesn't seem to work properly. In fact, when I add the token in the Authorize header then execute the query, it says loading indefinitely.
Loading request
I've been facing the same problem for 2 days and I don't find any topic dealing about my issue.
{
"swagger": "2.0",
"info": {
"description": "Swagger API",
"version": "1.0.0",
"title": "Swagger API",
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
},
"securityDefinitions": {
"Bearer": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
},
"paths": {
"/api/login": {
"post": {
"tags": ["Login"],
"summary": "Returns JWT",
"parameters": [
{
"in": "body",
"name": "Login body",
"description": "Login request used to obtain JWT",
"required": true,
"schema": {
"$ref": "#/components/Login"
}
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
},
"/api/devices": {
"get": {
"tags": ["Devices"],
"summary": "Returns all devices",
"security": {
"Bearer": []
},
"responses": {
"200": {
"description": "GET success"
},
"401": {
"description": "Missing header with jwt"
}
}
},
"post": {
"tags": ["Devices"],
"summary": "Deploy all devices",
"security": {
"Bearer": []
},
"parameters": [
{
"in": "body",
"name": "Devices POST body",
"description": "Deploy devices",
"required": true,
"schema": {
"$ref": "#/components/Devices"
}
}
],
"responses": {
"200": {
"description": "Device deployment succeed"
},
"401": {
"description": "Missing header with jwt"
}
}
}
}
},
"components": {
"Login": {
"type": "object",
"properties": {
"login": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
}
}
},
"Devices": {
"type": "object",
"properties": {
"devices": {
"type": "object",
"properties": {
"devEUILSBList": {
"type": "array",
"items": {
"type": "string"
}
},
"applicationID": {
"type": "integer"
},
"deviceProfileID": {
"type": "string"
}
}
}
}
}
}
}
Complementary information :
The backend is running with Flask
Swagger 2.0

AWS API Gateway fails to import Swagger definition: Unsupported model type 'MapProperty'

I am currently on this screen trying to import my app's swagger definition so I can create an API Gateway instance.
Unfortunately, you can see I'm getting some errors - even though swagger seems to think it's entirely fine.
Your API was not imported due to errors in the Swagger file.
Unable to create model for 200 response to method 'GET /api/v1/courses': Validation Result: warnings : [], errors : [Invalid content type specified: */*]
Unsupported model type 'MapProperty' in 200 response to method 'GET /api/v1/courses/all'. Ignoring.
Here is my swagger definition:
{
"swagger": "2.0",
"info": {
"description": "Api Documentation",
"version": "1.0",
"title": "Api Documentation",
"termsOfService": "urn:tos",
"contact": {},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
},
"host": "********.appspot.com",
"basePath": "/",
"tags": [{
"name": "course-controller",
"description": "Course Controller"
}],
"paths": {
"/api/v1/courses": {
"get": {
"tags": ["course-controller"],
"summary": "getCourses",
"operationId": "getCoursesUsingGET",
"produces": ["*/*"],
"parameters": [{
"name": "code",
"in": "query",
"description": "code",
"required": false,
"type": "string"
}],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Course"
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
},
"deprecated": false
}
},
"/api/v1/courses/all": {
"get": {
"tags": ["course-controller"],
"summary": "getAllCourses",
"operationId": "getAllCoursesUsingGET",
"produces": ["*/*"],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "object",
"additionalProperties": {
"type": "object"
}
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
},
"deprecated": false
}
}
},
"definitions": {
"Course": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"credits": {
"type": "integer",
"format": "int32"
},
"id": {
"type": "integer",
"format": "int32"
},
"lastUpdated": {
"type": "string"
},
"name": {
"type": "string"
},
"prerequisites": {
"type": "string"
},
"restrictions": {
"type": "string"
},
"seats": {
"$ref": "#/definitions/Seats"
},
"waitlist": {
"$ref": "#/definitions/Seats"
}
},
"title": "Course"
},
"Seats": {
"type": "object",
"properties": {
"actual": {
"type": "integer",
"format": "int32"
},
"capacity": {
"type": "integer",
"format": "int32"
},
"remaining": {
"type": "integer",
"format": "int32"
}
},
"title": "Seats"
}
}
}
Is there any reason you can find for this swagger definition breaking in API Gateway?
AWS API Gateway has some limitations in its OpenAPI support. For example, it does not support additionalProperties in models (this keyword is used in the 200 response schema for the /api/v1/courses/all endpoint in your API).
You can click the "Import and ignore warnings" button to ignore those errors and proceed with the import.

Validating request path parameter of AWS API gateway?

Let's say I have an api with paths / and /{pets} and /{pets}/pet. Now I'm trying to validate the path {pets} parameter so that only path having alphanumerical characters of length 6 will be validated and processed to the backend lambda all others will be rejected. I tried the following swagger schema specifying format and type for the parameter. I even tried using pattern in the schema but it seems to be not working. May I know how can we limit only path parameters of certain IDs.
{
......
"/{pets}/pet": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [{
"name": "pets",
"in": "path",
"required": true,
"schema": {
"type": "string",
"pattern": "[A-Za-z0-9]{6}"
}
}],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-request-validator": "Validate query string parameters and headers",
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"requestTemplates": {
"application/json": "## See ...."
},
"uri": "........",
"passthroughBehavior": "when_no_templates",
"httpMethod": "POST",
"contentHandling": "CONVERT_TO_TEXT",
"type": "aws"
}
}
}
.....
}
What I'm trying to achieve:
https://api.example.com/aacc77/pet -- Accept
https://api.example.com/aacc77s/pet -- Reject
https://api.example.com/aacc7/pet -- Reject
https://api.example.com/aacc_7/pet -- Reject
Basically, I want to use this regex pattern for the path [A-Za-z0-9]{6}.
"pets": {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Pets Schema",
"type": "string",
"pattern": "[A-Za-z0-9]{6}"
}
I see that there is a related question here, I wonder whether there is a solution available for this.

AWS API Gateway - HTTP Passthrough Path Parameters

I'm trying out the HTTP passthrough functionality in API gateway, passing through a resource method to another API. I want to pass through the path parameters from the API gateway URL to the backend API that also needs those path parameters.
I have the following simple Swagger document trying to test this out:
{
"swagger": "2.0",
"info": {
"version": "2017-09-15T03:33:48Z",
"title": "api-gateway-http-test"
},
"schemes": [
"https"
],
"paths": {
"/subresource/{name}": {
"get": {
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"uri": "http://my.web.service.url/subresource/{name}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "http_proxy",
"requestParameters": {
"integration.request.path.name": "method.request.path.name"
}
}
}
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
When I try deploying this to API Gateway via CloudFormation, API Gateway gives me this error:
Unable to put integration on 'GET' for resource at path '/subresource/{name}':
Invalid mapping expression specified:
Validation Result:
warnings : [], errors : [Invalid mapping expression parameter specified: method.request.path.name]
I've looked at various sources online, and this way of configuring the "requestParameters" section seems to be the recommended way to pass through path parameters to the backend API.
What am I missing here that would cause this to not work?
It is missing parameter definitions.
Check it out with the below,
{
"swagger": "2.0",
"info": {
"version": "2017-09-15T03:33:48Z",
"title": "api-gateway-http-test"
},
"schemes": [
"https"
],
"paths": {
"/subresource/{name}": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"uri": "http://google.com/subresource/{name}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "http_proxy",
"requestParameters": {
"integration.request.path.name": "method.request.path.name"
}
}
}
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}

Unable to execute Lambda in Async mode via API Gateway POST request

Why currently there no way to execute AWS Lambda in asynchronous mode via Gateway API without involving intermediary Lambda just for calling invoke() method?
Even if i add integration like this:
r = client.put_integration(
restApiId=rest_api_id,
resourceId=resource_id,
httpMethod='POST',
type='AWS',
integrationHttpMethod='POST',
uri=uri,
requestParameters={
'integration.request.header.X-Amz-Invocation-Type': "'Event'",
'integration.request.header.Invocation-Type': "'Event'"
}
)
It still executed synchronously...
Are there some platform limitation or so?
I have an example Swagger document which you can switch invocation type to Lambda function. I guess you already got how to map the header to trigger the different invocation types, but I think you might forget to deploy the API.
Swagger
{
"swagger": "2.0",
"info": {
"version": "2016-02-11T22:00:31Z",
"title": "LambdaAsync"
},
"host": "<placeholder>",
"basePath": "<placeholder>",
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "X-Amz-Invocation-Type",
"in": "header",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"x-amazon-apigateway-integration": {
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:<account>:function:<function_name>/invocations?Qualifier=$LATEST",
"responses": {
"default": {
"statusCode": "200"
}
},
"requestParameters": {
"integration.request.header.X-Amz-Invocation-Type": "method.request.header.X-Amz-Invocation-Type"
},
"type": "aws"
}
}
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}