Open API 3.0.1 One Of Examples Definition in SpringBoot RestAPI - spring-boot

I'm writing an OpenAPI spec for an existing API. This API returns status 400 for two different failure, but with a different response structure.I tried the following structure.
How to use oneOf example in OpenAPI 3.0.1 with Springboot Rest API?
get:
tags:
- pet
summary: Find pet by ID
description: Returns a single pet
operationId: getPetById
parameters:
- name: petId
in: path
description: ID of pet to return
required: true
schema:
type: integer
format: int64
responses:
'400':
description: Invalid ID supplied
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/ApiResultOk'
- $ref: '#/components/schemas/ApiResultError'
examples:
success:
summary: Example of a Test response 1
value:
errorCode: "1001"
errorMsg: "Error Message 1"
error:
summary: Example of an error response 2
value:
errorCode: "1002"
errorMsg: "Error Message 2"
components:
schemas:
ApiResultOk:
type: object
properties:
errorCode:
type: string
errorMsg:
type: string
ApiResultError:
type: object
properties:
errorCode:
type: string
errorMsg:
type: string
Edit : After generated maven plugin and removed oneOf (single schema)
#ApiOperation(value = "Find pet by ID", nickname = "getPetById", notes = "Returns a single pet", authorizations = {
#Authorization(value = "api_key")
}, tags={ "pet", })
#ApiResponses(value = {
#ApiResponse(code = 400, message = "Invalid ID supplied", response = ApiResult.class),
#ApiResponse(code = 404, message = "Pet not found") })
#RequestMapping(value = "/ticketReOpen/{ticketUUID}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public class ApiResult {
#JsonProperty("errorCode")
private String errorCode;
#JsonProperty("errorMsg")
private String errorMsg;
public ApiResult errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
#ApiModelProperty(value = "")
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public ApiResult errorMsg(String errorMsg) {
this.errorMsg = errorMsg;
return this;
}
#ApiModelProperty(value = "")
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
Swagger UI doesnt display 400 code response and examples

Related

TypeGraphQL: ArgumentValidationError on mutation

I'm playing around with TypeGraphQL and have a simple api setup to query projects and their associated clients.
For my createClient mutation, I'm receiving an ArgumentValidation Error, 'an unknown value was passed to the validate function' and can't pinpoint whats going wrong.
Client Schema
import { ObjectType, Field, ID } from "type-graphql";
#ObjectType()
class ClientSchema {
#Field(type => ID)
id: string
#Field()
name: string
#Field()
email: string
#Field()
phone: string
}
export default ClientSchema
Client Resolver
import { Arg, Field, InputType, Mutation, Query, Resolver } from "type-graphql";
import exampleClients from "../utils/clients";
import ClientSchema from "../schemas/ClientsSchema";
#InputType()
class CreateClassInput {
#Field()
name: string
#Field()
email: string
#Field()
phone: string
}
#Resolver()
class ClientResolver {
#Query((returns) => [ClientSchema])
async clients() {
return exampleClients;
}
#Query((returns) => ClientSchema)
async client(#Arg("id") id: string) {
const client = exampleClients.find((client) => client.id === id);
if (!client) throw new Error("No such client");
return client;
}
#Mutation((returns) => ClientSchema)
async createClient(#Arg("data") createClassData: CreateClassInput) {
const { name, email, phone } = createClassData;
const newClient: ClientSchema = {
id: String(exampleClients.length + 1),
name,
email,
phone
};
exampleClients.push(newClient);
return newClient;
}
}
export default ClientResolver;
GraphQL Query
mutation createClient {
createClient(data: { name: "Test Name", email: "Test Email", phone: "Test phone" }) {
name
}
}
If i pass the arguments to the mutation directly, without de-structuring an object, I don't get the error however with it I do. Is there something I'm doing wrong?

415Unsupported Media Type in endpoint generated by openapi 3.0

I've generated endpoint using openapi 3.0 that consumes form data. No idea what could have I done wrong, since its all generated and in past I've been able to upload file like this. The difference is that now I have multiple fields other than file.
paths:
/movie:
post:
operationId: createMovie
description: creates movie
requestBody:
content:
multipart/form-data:
schema:
$ref: '#/components/schemas/MovieRequest'
responses:
'200':
description: ''
content:
application/json:
schema:
$ref: '#/components/schemas/Movie'
Movie request component:
MovieRequest:
type: object
properties:
title:
type: string
description:
type: string
director:
type: string
length:
type: integer
format: int64
category:
$ref: '#/components/schemas/Category'
ageCategory:
$ref: '#/components/schemas/AgeCategory'
poster:
type: string
format: binary
trailerLink:
type: string
shortDescription:
type: string
Generated controller:
#ApiOperation(value = "", nickname = "createMovie", notes = "creates movie", response = MovieModelApi.class, tags={ })
#ApiResponses(value = {
#ApiResponse(code = 200, message = "", response = MovieModelApi.class) })
#RequestMapping(
method = RequestMethod.POST,
value = "/movie",
produces = { "application/json" },
consumes = { "multipart/form-data" }
)
default ResponseEntity<MovieModelApi> createMovie(#ApiParam(value = "") #Valid #RequestPart(value = "title", required = false) String title,#ApiParam(value = "") #Valid #RequestPart(value = "description", required = false) String description,#ApiParam(value = "") #Valid #RequestPart(value = "director", required = false) String director,#ApiParam(value = "", allowableValues = "HORROR") #Valid #RequestPart(value = "category", required = false) CategoryModelApi category,#ApiParam(value = "", allowableValues = "PG13") #Valid #RequestPart(value = "ageCategory", required = false) AgeCategoryModelApi ageCategory,#ApiParam(value = "") #Valid #RequestPart(value = "poster", required = false) MultipartFile poster) {
getRequest().ifPresent(request -> {
for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
String exampleString = "{ \"director\" : \"director\", \"isEnabled\" : true, \"description\" : \"description\", \"id\" : 5, \"title\" : \"title\", \"poster\" : \"poster\" }";
ApiUtil.setExampleResponse(request, "application/json", exampleString);
break;
}
}
});
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
After importing the yaml to postman I send request:
That contains headers:
But I get 415 unsupported media error
HTTP 415 Unsupported Media Type indicates that the server is refusing to accept the request because the payload format is not supported. The format problem may be related to the Content-Type or Content-Encoding specified in the request, or as a result of direct validation of the data.

Graphql dynamic key type

I'm trying to create a type of this object
const obj = {
0: {
title: 'lorem',
description: 'ipsum',
},
1: {
title: 'dolor',
description: 'sit',
},
...
}
Copilot suggest me this but didn't work, it's very similar to what need to do
type Spec {
title: String
description: String
}
type Specs {
[key: number]: Spec
}
type Product {
specs: Specs
}

How to set the Apollo GraphQL server to accept an object as a variable to a mutation?

Currently, I'm trying to pass an object as a variable to a mutation as shown below:
type ShopLocation {
lane1: String
lane2: String
city: String
postalCode: String
country: String
}
type ShopResponse {
statusCode: Int
messageCode: String
data: String
}
type Mutation {
createShop(
name: String
email: String
location: ShopLocation
): ShopResponse
}
But I get the following error:
{
"error": {
"errors": [
{
"message": "The type of Mutation.createShop(location:) must be Input Type but got: ShopLocation.",
"extensions": {
"code": "GRAPHQL_VALIDATION_FAILED",
"exception": {
"stacktrace": [
"Error: The type of Mutation.createShop(location:) must be Input Type but got: ShopLocation.",
" at assertValidSchema (.../node_modules/graphql/type/validate.js:71:11)",
" at Object.validate (.../node_modules/graphql/validation/validate.js:55:35)",
" at Promise.resolve.then (.../node_modules/apollo-server-core/src/runQuery.ts:188:30)",
" at <anonymous>",
" at process._tickDomainCallback (internal/process/next_tick.js:228:7)"
]
}
}
}
]
}
}
Any idea how to properly do this?
You need to make the ShopLocation with input keyword instead of type,
input ShopLocationInput {
lane1: String
lane2: String
city: String
postalCode: String
country: String
}
type ShopResponse {
statusCode: Int
messageCode: String
data: String
}
type Mutation {
createShop(
name: String
email: String
location: ShopLocationInput
): ShopResponse
}

Customise WebAPI response like Status, Data, message formate

How can i customise WebAPI 2 response like status, data, message in JSON format
Successful request:
{
"status": "success",
"data": {
/* Application-specific data would go here. */
},
"message": null /* Or optional success message */
}
Failed request:
{
"status": "error",
"data": null, /* or optional error payload */
"message": "Error xyz has occurred"
}
Define a new class like :
public class ResponseDto
{
public string status { get; set; }
public dynamic data { get; set; }
public string message { get; set; }
}
and then populate the properties with respective values and do :
var response = new ResponseDto()
{
response.status = " ",
response.data = obj,
response.message = " "
}
and then from the controller method(API),
return response;
Your JSON formatter will then convert the response object into JSON string.

Resources