Raml 1.0 Types with examples and mulesoft mocking service - raml

I am using RAML 1.0 in the mulesoft api designer.
I would like to use types/properties to describe my api responses, and also enable the mocking service so I can run the api and get back an example response. I thought if I gave the type an example value the mocking service would be able to generate the example json response. This is my test raml
#%RAML 1.0
title: Test
baseUri: https://mocksvc.mulesoft.com/mocks/<removed>
types:
Email:
description: Email address
example: Steve#test.com
/user:
get:
responses:
200:
body:
application/json:
properties:
email: Email
When I run the api through the mocking service, I expect my response body to be this:
{
"email": "Steve#test.com"
}
but the service reports that it has no information and returns this in the body
{
"message": "RAML had no response information for application/json"
}

No, it would be a cool feature but it doesn't work that way.
You need to add the example in the response:
...
types:
Email:
description: Email address
/user:
get:
responses:
200:
body:
application/json:
properties:
email: Email
example: { "email": "Steve#test.com" }

We need to provide the example type we are expecting, check this link http://raml.org/developers/raml-200-tutorial
below just added example in response body, there we can provide multiple outcomes to.
%RAML 1.0
title: Test
baseUri: https://mocksvc.mulesoft.com/mocks/
types:
Email:
description: Email address
example: Steve#test.com
/user:
get:
responses:
200:
body:
application/json:
properties:
email: Email
example:
"email" : [
{ "email" : "Steve#test.com"}
]

Types tag in Raml 1.0 is more powerful. You have design your custom type as per comfort and also increase reputability of the code
#%RAML 1.0
title: Brochure
version: v1
baseUri: https://mocksvc.mulesoft.com/mocks/63063930-851d-41cc-b021-36d8a435d800 # baseUri: http://localhost:8080
protocols: HTTP
mediaType: application/json
types:
ModelTree:
type: object
properties:
modelTreeReference: string
brand: string
series?: string
constructionSeries?: string
bodyType?: string
AGModelCode?: string
UKModelCode?: string
levelCode?: number
Brochure:
type: object
properties:
recordNumber: number
partNumber: number
name: string
brand: string
brochureType: string
CRMGroup: string
CRMSubGroup: string
isActiveIndicator: string
modelTree: ModelTree
Status:
type: object
properties:
responseStatus:
enum: [COMPLETE, ERROR, FATAL]
responseId: number
Transaction:
type: object
properties:
status: Status
data:
type: object
properties:
brochures?: Brochure[]
/brochures:
get:
responses:
200:
description: Status and a list of Brochures
body:
application/json:
example: {
status: {
responseStatus: 'COMPLETE',
responseId: 123
},
data: {
brochures: [{
recordNumber: 1,
partNumber: 56,
name: "Activity Brochure",
brand: "My Brand Ltd",
brochureType: "HARDCOPY",
CRMGroup: "Sales",
CRMSubGroup: "Lifestyle/Access",
isActiveIndicator: "N",
modelTree: {
modelTreeReference: "My Brand",
brand: "My Brand Ltd",
levelCode: 1
}
}
]
}
}
type: Transaction

I ran into a similar issue using examples with a form encoded body. The examples given in the spec and the RAML 200 tutorial for application/json encoded responses don't work for application/x-www-form-urlencoded.
This type
types:
hub:
type: object
properties:
callback: string
mode:
enum: ["subscribe", "unsubscribe"]
topic: string
works properly with an application/json body and example
/subv1json:
post:
description: "Subscribes to a topic"
body:
application/json:
type: hub
example:
{
"callback": "http://yourcallback.url.com",
"mode": "subscribe",
"topic": "orders"
}
responses:
202:
Returns: 202 Accepted
but changing the encoding to x-www-form-urlencoded
/subv1form: #this doesn't work, returns 400 bad request
post:
description: "Subscribes to a topic"
body:
application/x-www-form-urlencoded:
type: hub
example:
{
"callback": "http://yourcallback.url.com",
"mode": "subscribe",
"topic": "orders"
}
responses:
202:
Returns 400 Bad Request and a syntax error
{
"code": "REQUEST_VALIDATION_ERROR",
"message": "Invalid schema for content type application/x-www-form-urlencoded. Errors: Syntax error in the following text: '}: { "callback": "http://yourcallback.url.com", "mode": "subscribe",'. "
}
I found that moving the example inside of the type definition didn't help - only changed the error to a more precise 'require key [mode] not found'
{
"code": "REQUEST_VALIDATION_ERROR",
"message": "Invalid schema for content type application/x-www-form-urlencoded. Errors: required key [mode] not found. "
}
However, reformatting the sample to yaml syntax does work, but requires that you do NOT specify the example in the type.
/subv3examplereformatted: #this works
post:
description: "Subscribes to a topic"
body:
application/x-www-form-urlencoded:
type: hub
example:
id: "example1"
callback: "http://yourcallback.com"
mode: "subscribe"
topic: "order"
responses:
202:
So, there is quirky-ness to how the mocking services manage serializing examples for form encoded parameters, and more than one way to provide examples. This is one work around if you want to use x-www-form-urlencoded and provide examples that work in the mocking services.

Related

Spring boot code generated from swaggerhub is not able to throw 400 on additional properties

I've logged in to swaggerhub and generated a sample inventory API which is part of their template.
In codegen options selected spring as server. ticked on useBeanValidation checkbox. Generated the code, tested it. Validations are working properly as expected except only one thing. I don't want to allow any additional property on the POST payload.
NB: The openAPI specification doesn't have 'additionalProperties' flag specified. Which defaults it to 'false' in my understanding. I tried to explicitly specify the same too. but no luck. There is no exception thrown while I add an additionalProperty.
The OpenAPI specification
openapi: 3.0.0
servers:
# Added by API Auto Mocking Plugin
- description: SwaggerHub API Auto Mocking
url: https://virtserver.swaggerhub.com/xxxx/apionopenApi3/1.0.0
info:
description: This is a simple API
version: "1.0.0"
title: Simple Inventory API
contact:
email: you#your-company.com
license:
name: Apache 2.0
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: admins
description: Secured Admin-only calls
- name: developers
description: Operations available to regular developers
paths:
/inventory:
get:
tags:
- developers
summary: searches inventory
operationId: searchInventory
description: |
By passing in the appropriate options, you can search for
available inventory in the system
parameters:
- in: query
name: searchString
description: pass an optional search string for looking up inventory
required: false
schema:
type: string
- in: query
name: skip
description: number of records to skip for pagination
schema:
type: integer
format: int32
minimum: 0
- in: query
name: limit
description: maximum number of records to return
schema:
type: integer
format: int32
minimum: 0
maximum: 50
responses:
'200':
description: search results matching criteria
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/InventoryItem'
'400':
description: bad input parameter
post:
tags:
- admins
summary: adds an inventory item
operationId: addInventory
description: Adds an item to the system
responses:
'201':
description: item created
'400':
description: 'invalid input, object invalid'
'409':
description: an existing item already exists
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/InventoryItem'
description: Inventory item to add
components:
schemas:
InventoryItem:
type: object
additionalProperties: False
required:
- id
- name
- manufacturer
- releaseDate
properties:
id:
type: string
format: uuid
example: d290f1ee-6c54-4b01-90e6-d701748f0851
name:
type: string
example: Widget Adapter
releaseDate:
type: string
format: date-time
example: '2016-08-29T09:12:33.001Z'
manufacturer:
$ref: '#/components/schemas/Manufacturer'
Manufacturer:
required:
- name
properties:
name:
type: string
example: ACME Corporation
homePage:
type: string
format: url
example: 'https://www.acme-corp.com'
phone:
type: string
example: 408-867-5309
type: object
additionalProperties: False
Got 400 for this payload on post API.
{
"id": "7f125802-7840-4ff0-8ddb-7c78c0948987",
"name11111": "Widget Adapter",
"releaseDate": "2016-08-29T09:12:33.001Z",
"manufacturer": {
"name": "ACME Corporation",
"homePage": "",
"phone": "408-867-5309"
}
}
Expected 400 but didn't get on this payload on post
{
"id": "7f125802-7840-4ff0-8ddb-7c78c0948983",
"name": "Widget Adapter",
"releaseDate": "2016-08-29T09:12:33.001Z",
"manufacturer": {
"name": "ACME Corporation",
"homePage": "",
"phone": "408-867-5309"
},
"newkey" : "newValue"
}
Can anybody pls help on this.. I want to completely disallow additional properties and throw a 400 on those requests..
The default for additionalProperties is actually True, not False.
Adding false does not cause the swagger-codegen for Spring to actually disallow additional fields though, annoyingly enough. After a few hours of running in the wrong direction I found the solution:
In application.properties
spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true
I had been having the same trouble and have tried to leverage filters but have had problems tying the models that are used in the automatic deserialization of #RequestBody to the servlet request and keeping the behavior consistent across model changes. Coming to that conclusion required writing quite a bit of unnecessary boilerplate and wasting a lot of time.
I also tried to find a way to inject some behavior in the automatic use of the model or any model annotation that would change how the model automatically disregards additional fields without reporting the bad request. After exhausting the road of annotations I found the solution.

How to validate JSON payload against OpenApi specification from Ruby?

I have HTTP request payload structured according to jsonapi.org guidelines:
{
"data": {
"type": "employee",
"attributes": {
"firstName": "John",
"lastName": "Doe",
}
}
}
then I have OpenApi specification (yaml) of this payload:
employee:
type: object
required: [data]
properties:
data:
type: object
properties:
type:
type: string
enum: [employee]
attributes:
type: object
required: [firstName, lastName]
properties:
firstName:
type: string
example: 'John'
lastName:
type: string
example: 'Doe'
and what I want is to validate the payload against the specification (from Ruby/Rails).
there exist openapi3_parser gem, but that one seems to be capable only to validate the specification, not the actual payload.
then, there are jsonapi.org payload deserializers, but those do not seem to take care about OpenApi formal specification at all.
I use OpenApi to describe the payload becuase I get http API docs for free via Swagger.
it can be achieved by using json-schema, e.g.:
errors = JSON::Validator.fully_validate(schema, payload)
(it is working for me with json-schema gem 2.8.1, schema itself is written in openapi v 2.0)
This gem https://github.com/interagent/committee validates requests/responses based off of an open api spec you provide.

Swagger using the same model but different examples

My API can retun 200 ok or 400, an error occurred. I want them both to use the same model but different examples. In my code below, I want my 200 Info to say something like "All ok" and 400's Info "Not ok".
responses:
'200':
description: >-
Invoice received for processing but beware of potentional warnings
and information
schema:
$ref: '#/definitions/Response'
'400':
description: Invoice could not be processed due to fatal errors
schema:
$ref: '#/definitions/Response'
Response:
type: object
properties:
Info:
type: string
information
Messages:
type: object
properties:
Fatal:
type: array
items:
type: object
Warning:
type: array
items:
type: object
Information:
type: array
items:
type: object
In OpenAPI 2.0, responses support the examples keyword to specify response examples for different HTTP status codes and media types.
responses:
'200':
description: >-
Invoice received for processing but beware of potential warnings
and information
schema:
$ref: '#/definitions/Response'
examples:
application/json:
Info: OK
# Or using JSON syntax for the example value:
# application/json: {"Info": "OK"}
'400':
description: Invoice could not be processed due to fatal errors
schema:
$ref: '#/definitions/Response'
examples:
application/json:
Info: Oops
Messages:
Fatal:
- Houston, we have a problem
# Or using JSON syntax for the example value:
# application/json:
# {
# "Info": "Oops",
# "Messages": [
# {
# "Fatal": [
# {"Custom error": "Houston, we have a problem"}
# ]
# }
# ]
# }

what does "content" : mean in swagger/openapi "responses":

Using Swagger/OpenAPI (and subsequently swagger-codegen) I haven't been able to find what the difference should be between
This, taken direclty from https://swagger.io/specification/#responsesObject
(first example, json format)
"responses" : {
"200": {
"description": "a pet to be returned",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
} } } } }
and
"responses" : {
"200": {
"description": "a pet to be returned",
"schema": {
"$ref": "#/components/schemas/Pet"
} } }
I've put this example into a trivial json swagger spec (json) and run the Swagger-Codegen (python, flask) to generate my controllers and model. Yaml seems to be the preferred internal representation, so when the generator runs it creates a yaml file.
With the former, the response type is "None"
responses:
200:
description: "a pet to be returned"
whereas the latter yields what I think I should be expecting:
responses:
200:
description: "a pet to be returned"
schema:
$ref: "#/components/schemas/Pet"
eg, the schema seems to be omitted from the first syntax using Content
What does content mean?
What am i missing from the example, why doesn't the Content result in a non-None return type and corresponding schema.
Note on the SwaggerCodgen: the generated code matches exactly what the generated yaml says, hence I haven't included any of those details here
The first example is OpenAPI 3.0, the second example is OpenAPI 2.0, hence the difference.
The content keyword used in OpenAPI 3.0 is a replacement for consumes/produces from OpenAPI 2.0. In the context of responses, content means that the response has a body and specifies the media type (JSON/XML/etc.) and structure of the response body.
OpenAPI 2.0 version:
swagger: "2.0"
...
paths:
/foo:
get:
produces:
- application/json
responses:
200:
description: OK
schema:
$ref: "#/definitions/Pet"
OpenAPI 3.0 version:
openapi: 3.0.0
...
paths:
/foo:
get:
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
The codegen issue is likely caused by any of the fololowing:
codegen does not support OpenAPI 3.0 yet
the spec is not valid (e.g. uses a mix of 2.0 and 3.0 keywords)

Putting arrays inside of objects using Swagger 2.0 and YAML

I am currently learning how to document using Swagger because my company is evaluating using it as a standard way of documenting for upcoming projects.
I read online that using YAML is easier to read than using JSON, and since YAML is a subset of JSON I figured it would be alright.
I'm working on the response for the 200 code, I would like to represent something similar to the following structure:
responses:
200:
description: OK.
schema:
title: response
type: object
items:
properties:
title: user
type: array
items:
id:
type: string
name:
type: string
status:
type: integer
Basically I return an object called "response" that contains two variables: An array called "user" that contains several strings (I included just two for the sake of clarity) and another variable (outside of the "user" array) called "status" that contains an integer.
The above code doesn't work, and the editor notifies me that it isn't a "valid response definition".
I'm not sure how to tackle this. I'd appreciate some help on what I'm doing wrong.
Basically I return an object called "response" that contains two variables: An array called "user" that contains several strings (I included just two for the sake of clarity) and another variable (outside of the "user" array) called "status" that contains an integer.
Based on your description, the response is supposed to be as follows (assuming the response is JSON). Basically, you have an object with a nested object:
{
"user": {
"id": "12345",
"name": "Alice"
},
"status": 0
}
This response can be defined as follows:
responses:
200:
description: OK.
schema:
title: response
type: object
required: [user, status]
properties:
user:
type: object
required: [id, name]
properties:
id:
type: string
name:
type: string
status:
type: integer
For convenience, complex schemas with nested objects can be broken down into individual object schemas. Schemas can be written in the global definitions section and referenced from other places via $ref. This way, for example, you can reuse the same schema in multiple operations/responses.
responses:
200:
description: OK.
schema:
$ref: "#/definitions/ResponseModel"
definitions:
ResponseModel:
title: response
type: object
properties:
user:
$ref: "#/definitions/User"
status:
type: integer
required:
- user
- status
User:
type: object
properties:
id:
type: string
name:
type: string
required:
- id
- name

Resources