I am working on a project that uses Swagger 2.0 to generate an API interface which is then implemented in production code. There is a problem with a parameter that comes from the header.
There are 2 desired behaviors -
If a value is provided and does not match the enum, it should throw an error
If no value is provided, it should be given the default value of 'English'
Here is the code -
parameters:
language:
in: header
name: language
description: language the request will be processed in
type: string
default: English
enum: [English, Spanish, German, French]
required: false
However, the API accepts any value and does not provide a default value.
The generated code does not give any hint that it should be an enum. It does show the default value but did not provide it when I performed an integration test.
#ApiParam(value = "language the request will be processed in" , defaultValue="English") #RequestHeader(value="language", required=false) String language);
I found other similiar questions on here but no answers -
Swagger does not validate enum query parameter
Related
In my previous post
How to accept multiple query parameters with different parameter name in one class
I learned about passing the query parameters, and I also achieved it
But now the problem is I am in a swagger setup where I use codegen for generating API default code which provides me an interface using which I implement it into my controller layer and overrides those methods and add my logic
The problem is I have an internal api-doc file that generates a custom code, in that file how should I mention that I am using my own custom class for passing it to be used as a query parameter object? Currently, my api doc file looks like below. Problem with below file is I have to define each and every query parameter and as I learned in my previous stack article that we can wrap it into an class object. But my question here is how should I mention path to my custom class into this file.
/tasks:
get:
parameters:
- $ref: 'api-params.yaml#/name'
- $ref: 'api-params.yaml#/age'
- $ref: 'api-params.yaml#/credentials'
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: 'api-resp.yaml#/someResponse'
"401":
description: "Unauthorized"
content: { }
"403":
description: "Forbidden"
content: { }
And also can we directly define a model using swagger? If yes how can we do that?
I mean I am using custom models for referring them to be used as request body and I usually mention them like below, but my question is can we use similar behaviour for queryParams also
schema:
$ref: '#/components/schemas/RquestBodyPayload'
but is the similar this is also allowed for query parameters ?
I'm learning creating rest Api using spring boot. FOr reference I was checking some existing code where in yaml file I found two parameters mentioned below
name: "name"
in: "query"
description: "doing something"
x-phase-dataelem: "CONF//Y/N"
required: false
schema:
type: string
maxlength:15
name: "tame"
in: "header"
description: "doing something something"
x-phase-dataelem: "CONF//Y/N"
required: true
schema:
type: string
maxlength:15
am literally not able to understand these parameters
in: "query"
in: "header"
x-phase-dataelem: "CONF//Y/N"
I know that, these are some values which are being passed to client url to process, but not able to understand these parameters. what's significance of using these 3 parameters ?
can anyone help ?
This YAML snippet looks like a Swagger/OpenAPI contract. You can find more about OpenAPi and read its specification here - https://swagger.io/specification/
in describes the location of the HTTP parameter.
Quote from the OpenAPI specification:
There are four possible parameter locations specified by the in
field:
path - Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include
the host or base path of the API. For example, in /items/{itemId}, the
path parameter is itemId.
query - Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
header - Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive.
cookie - Used to pass a specific cookie value to the API.
Regarding the x-phase-dataelem, it is a custom extension in your OpenAPI contract. It is used for providing some additional metadata/information/properties about the described items (including parameters).
Quote from the OpenAPI specification:
While the OpenAPI Specification tries to accommodate most use cases,
additional data can be added to extend the specification at certain
points.
The extensions properties are implemented as patterned fields that are always prefixed by x-, for example, x-internal-id. The value can be null, a primitive, an array or an object. Can have any valid JSON format value.
I am working on a Spring project that allows users to download CSV files from an endpoint.
OpenAPI Generator is used for code generation.
According to the "Response That Returns a File" section of the documentation, the schema for the response can be defined as type: string with format: binary. The generated interface would then be something like:
CompletableFuture<ResponseEntity<org.springframework.core.io.Resource>> downloadFile().
How can we specify an alternative body type for ResponseEntity? (e.g. StreamingResponseBody described in this blog)
The OpenAPI Generator has a configuration option named typeMappings which allows you to change the default mapping of OpenApi primitive types (such as array, float, etc...) to the corresponding java class (java.util.List, Float, ...).
In your particular case, you could try to map the "binary" type to something different from "java.util.File".
The default mappings are defined here - see as from line 1464
The API for which I'm writing a Swagger 2.0 specification is basically a store for any JSON value.
I want a path to read value and a path to store any JSON values (null, number, integer, string, object, array) of non-predefined depth.
Unfortunately, it seems that Swagger 2.0 is quite strict on schemas for input and output and does not allow the whole set of schemas allowed by JSON Schema. The Swagger editor doesn't allow for example mixed values (for example a property that can be either a boolean or an integer) or loosely defined arrays (the type of items must be strictly defined) and objects.
So I'm trying a workaround by defining a MixedValue schema:
---
swagger: '2.0'
info:
version: 0.0.1
title: Data store API
consumes:
- application/json
produces:
- application/json
paths:
/attributes/{attrId}/value:
parameters:
- name: attrId
in: path
type: string
required: true
get:
responses:
'200':
description: Successful.
schema:
$ref: '#/definitions/MixedValue'
put:
parameters:
- name: value
in: body
required: true
schema:
$ref: '#/definitions/MixedValue'
responses:
responses:
'201':
description: Successful.
definitions:
MixedValue:
type: object
properties:
type:
type: string
enum:
- 'null'
- boolean
- number
- integer
- string
- object
- array
boolean:
type: boolean
number:
type: number
integer:
type: integer
string:
type: string
object:
description: deep JSON object
type: object
additionalProperties: true
array:
description: deep JSON array
type: array
required:
- type
But the Swagger Editor refuses the loosely defined object and array properties.
Questions:
- Is there a way to workaround this issue?
- Is it just a Swagger Editor bug or a strong limit of the Swagger 2.0 spec?
- Is there a better way (best practice) to specify what I need?
- Can I expect some limitations in code produced by swagger for some languages with my API spec?
An arbitrary-type schema can be defined using an empty schema {}:
# swagger: '2.0'
definitions:
AnyValue: {}
# openapi: 3.0.0
components:
schemas:
AnyValue: {}
or if you want a description:
# swagger: '2.0'
definitions:
AnyValue:
description: 'Can be anything: string, number, array, object, etc. (except `null`)'
# openapi: 3.0.0
components:
schemas:
AnyValue:
description: 'Can be anything: string, number, array, object, etc., including `null`'
Without a defined type, a schema allows any values. Note that OpenAPI 2.0 Specification does not support null values, but some tools might support nulls nevertheless.
In OpenAPI 3.0, type-less schemas allow null values unless nulls are explicitly disallowed by other constraints (such as an enum).
See this Q&A for more details on how type-less schemas work.
Here's how Swagger Editor 2.0 handles a body parameter with the AnyValue schema:
I don't know how code generators handle this though.
Maybe this is what your are looking for "Patterned Objects":
Field Pattern: ^x-
Type: Any
Description: Allows extensions to the Swagger Schema. The field name MUST begin with x-, for example, x-internal-id. The value can be null, a primitive, an array or an object. See Vendor Extensions for further details.
Source: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
Given a Google Cloud Endpoints project in Eclipse with the servlet-class annotated with #Api(name="helloworld"), the Endpoints framework generates a file named war/WEB-INF/helloworld-v1.api when the project compiles successfully. Sometimes this file is not generated even if there are no compilation errors though - only what I will call "GAE Endpoints code convention errors".
Example - working:
public class TestEntity {
public String Text;
public TestEntity(String text){
Text = text;
}
}
#ApiMethod
public TestEntity getTestEntity(){
return new TestEntity("Hello world");
}
Example - NOT working:
// The TestEntity-class is unchanged
#ApiMethod
public TestEntity getTestEntity(String input){
return new TestEntity("Hello world");
}
The problem with the latter example is that I take a String parameter as input without annotating it with #Named. I know that in this example, but there might be other cases where this is not so obvious.
Is there anywhere where I can read some sort of error log on why the .api file is not generated?
Although I am a fan of code by convention, it really takes the programming efficiency a step back if I cannot get feedback on what I do wrong. Eclipse provides compiler error feedback. The Google Cloud Endpoints Framework should provide Code-By-Convention-Rule-Breaking feedback.
There isn't currently good logging or error messaging when code generation fails, though it's one of the (if not most) requested features. In the interim, here's a list of the common failure cases:
The return type is invalid. Return types must be objects conforming to JavaBean conventions, and types like Object, String, and Integer are not allowed.
One or more argument types are invalid. Methods may accept at most one object in the POST body, and this object should also conform to JavaBean conventions. Methods may accept zero or more arguments via the query string (using the #Named annotation) and these must be scalar types (e.g. String, Integer).
An API, method, or parameter has an invalid name. APIs, methods, and parameters should be named to match the following regular expression: [a-z]+[A-Za-z0-9]*. Convention also suggests using lowerCamelCase for naming (though alllowercase is allowed).