Java Code Examples for io.swagger.v3.oas.models.responses.ApiResponses#addApiResponse()

The following examples show how to use io.swagger.v3.oas.models.responses.ApiResponses#addApiResponse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Merge operation operation.
 *
 * @param operation the operation
 * @param operationModel the operation model
 * @return the operation
 */
public Operation mergeOperation(Operation operation, Operation operationModel) {
	if (operationModel.getOperationId().length() < operation.getOperationId().length()) {
		operation.setOperationId(operationModel.getOperationId());
	}

	ApiResponses apiResponses = operation.getResponses();
	for (Entry<String, ApiResponse> apiResponseEntry : operationModel.getResponses().entrySet()) {
		if (apiResponses.containsKey(apiResponseEntry.getKey())) {
			Content existingContent = apiResponses.get(apiResponseEntry.getKey()).getContent();
			Content newContent = apiResponseEntry.getValue().getContent();
			if (newContent != null)
				newContent.forEach((mediaTypeStr, mediaType) -> SpringDocAnnotationsUtils.mergeSchema(existingContent, mediaType.getSchema(), mediaTypeStr));
		}
		else
			apiResponses.addApiResponse(apiResponseEntry.getKey(), apiResponseEntry.getValue());
	}
	return operation;
}
 
Example 2
Source File: OperationContext.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
public void correctResponse(ApiResponses apiResponses) {

    if (apiResponses == null) {
      return;
    }

    // no annotations are processed
    // generate a default response based on the method return value
    if (apiResponses.get(HttpStatuses.OK) == null) {
      ApiResponse apiResponse = new ApiResponse();

      Class<?> returnType = method.getReturnType();
      if (returnType == Void.TYPE || returnType == Void.class) {
        return;
      }

      MediaType mediaType = new MediaType();

      Schema refSchema = ModelConverter.getSchema(returnType, getComponents(), RequestResponse.RESPONSE);
      mediaType.schema(refSchema);

      Content content = new Content();
      content.addMediaType(MediaTypes.APPLICATION_JSON, mediaType);
      apiResponse.description("OK");
      apiResponse.setContent(content);
      apiResponses.addApiResponse(HttpStatuses.OK, apiResponse);
    }
  }
 
Example 3
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets api responses.
 *
 * @param responses the responses
 * @param methodAttributes the method attributes
 * @param operation the operation
 * @param components the components
 * @return the api responses
 */
private Optional<ApiResponses> getApiResponses(
		final io.swagger.v3.oas.annotations.responses.ApiResponse[] responses,
		MethodAttributes methodAttributes, Operation operation, Components components) {

	ApiResponses apiResponsesObject = new ApiResponses();
	String[] classProduces = methodAttributes.getClassProduces();
	String[] methodProduces = methodAttributes.getMethodProduces();

	ApiResponses apiResponsesOp = operation.getResponses();

	for (io.swagger.v3.oas.annotations.responses.ApiResponse response : responses) {
		ApiResponse apiResponseObject = new ApiResponse();
		if (StringUtils.isNotBlank(response.ref())) {
			setRef(apiResponsesObject, response, apiResponseObject);
			continue;
		}
		setDescription(response, apiResponseObject);
		setExtensions(response, apiResponseObject);

		buildResponseContent(methodAttributes, components, classProduces, methodProduces, apiResponsesOp, response, apiResponseObject);

		AnnotationsUtils.getHeaders(response.headers(), null).ifPresent(apiResponseObject::headers);
		// Make schema as string if empty
		calculateHeader(apiResponseObject);
		if (isResponseObject(apiResponseObject)) {
			setLinks(response, apiResponseObject);
			if (StringUtils.isNotBlank(response.responseCode())) {
				apiResponsesObject.addApiResponse(response.responseCode(), apiResponseObject);
			}
			else {
				apiResponsesObject._default(apiResponseObject);
			}
		}
	}

	return Optional.of(apiResponsesObject);
}
 
Example 4
Source File: OperationBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Sets ref.
 *
 * @param apiResponsesObject the api responses object
 * @param response the response
 * @param apiResponseObject the api response object
 */
private void setRef(ApiResponses apiResponsesObject, io.swagger.v3.oas.annotations.responses.ApiResponse response,
		ApiResponse apiResponseObject) {
	apiResponseObject.set$ref(response.ref());
	if (StringUtils.isNotBlank(response.responseCode())) {
		apiResponsesObject.addApiResponse(response.responseCode(), apiResponseObject);
	}
	else {
		apiResponsesObject._default(apiResponseObject);
	}
}
 
Example 5
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Compute response from doc map.
 *
 * @param components the components
 * @param methodParameter the method parameter
 * @param apiResponsesOp the api responses op
 * @param methodAttributes the method attributes
 * @return the map
 */
private Map<String, ApiResponse> computeResponseFromDoc(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
		MethodAttributes methodAttributes) {
	// Parsing documentation, if present
	Set<io.swagger.v3.oas.annotations.responses.ApiResponse> responsesArray = getApiResponses(methodParameter.getMethod());
	if (!responsesArray.isEmpty()) {
		methodAttributes.setWithApiResponseDoc(true);
		for (io.swagger.v3.oas.annotations.responses.ApiResponse apiResponseAnnotations : responsesArray) {
			String httpCode = apiResponseAnnotations.responseCode();
			ApiResponse apiResponse = new ApiResponse();
			if (StringUtils.isNotBlank(apiResponseAnnotations.ref())) {
				apiResponse.$ref(apiResponseAnnotations.ref());
				apiResponsesOp.addApiResponse(apiResponseAnnotations.responseCode(), apiResponse);
				continue;
			}
			apiResponse.setDescription(propertyResolverUtils.resolve(apiResponseAnnotations.description()));
			buildContentFromDoc(components, apiResponsesOp, methodAttributes, apiResponseAnnotations, apiResponse);
			Map<String, Object> extensions = AnnotationsUtils.getExtensions(apiResponseAnnotations.extensions());
			if (!CollectionUtils.isEmpty(extensions))
				apiResponse.extensions(extensions);
			AnnotationsUtils.getHeaders(apiResponseAnnotations.headers(), methodAttributes.getJsonViewAnnotation())
					.ifPresent(apiResponse::headers);
			apiResponsesOp.addApiResponse(httpCode, apiResponse);
		}
	}
	return apiResponsesOp;
}
 
Example 6
Source File: GenericResponseBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build api responses.
 *
 * @param components the components
 * @param methodParameter the method parameter
 * @param apiResponsesOp the api responses op
 * @param methodAttributes the method attributes
 * @param httpCode the http code
 * @param apiResponse the api response
 * @param isGeneric the is generic
 */
private void buildApiResponses(Components components, MethodParameter methodParameter, ApiResponses apiResponsesOp,
		MethodAttributes methodAttributes, String httpCode, ApiResponse apiResponse, boolean isGeneric) {
	// No documentation
	if (StringUtils.isBlank(apiResponse.get$ref())) {
		if (apiResponse.getContent() == null) {
			Content content = buildContent(components, methodParameter, methodAttributes.getMethodProduces(),
					methodAttributes.getJsonViewAnnotation());
			apiResponse.setContent(content);
		}
		else if (CollectionUtils.isEmpty(apiResponse.getContent()))
			apiResponse.setContent(null);
		if (StringUtils.isBlank(apiResponse.getDescription())) {
			setDescription(httpCode, apiResponse);
		}
	}
	if (apiResponse.getContent() != null
			&& ((isGeneric || methodAttributes.isMethodOverloaded()) && methodAttributes.isNoApiResponseDoc())) {
		// Merge with existing schema
		Content existingContent = apiResponse.getContent();
		Type type = ReturnTypeParser.getType(methodParameter);
		Schema<?> schemaN = calculateSchema(components, type,
				methodAttributes.getJsonViewAnnotation(), methodParameter.getParameterAnnotations());
		if (schemaN != null && ArrayUtils.isNotEmpty(methodAttributes.getMethodProduces()))
			Arrays.stream(methodAttributes.getMethodProduces()).forEach(mediaTypeStr -> mergeSchema(existingContent, schemaN, mediaTypeStr));
	}
	apiResponsesOp.addApiResponse(httpCode, apiResponse);
}
 
Example 7
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 * Add openAPI path item to the the openAPI object.
 *
 * @param path            name of the pathItem
 * @param scopes          array of operation scopes
 * @param throttlingTier throttling tier
 */
void addOpenAPIPath(String path, String[] scopes, String throttlingTier) {
    PathItem pathItem = new PathItem();
    Operation operation = new Operation();
    operation.setOperationId(UUID.randomUUID().toString());
    addOauth2SecurityRequirement(operation, scopes);
    if (StringUtils.isNotEmpty(throttlingTier)) {
        operation.addExtension(OpenAPIConstants.THROTTLING_TIER, throttlingTier);
    }
    //needs to add the basic Auth Requirement to the operation level because if scopes are mentioned,
    // there would be oauth2 security requirement in method level.
    if (isBasicAuthEnabled) {
        addBasicAuthSecurityRequirement(operation);
    }
    if (isAPIKeyEnabled) {
        addAPIKeySecurityRequirement(operation);
    }
    //For each path, the only available http method is "post" according to the grpc mapping.
    pathItem.setPost(operation);
    if (openAPI.getPaths() == null) {
        openAPI.setPaths(new Paths());
    }
    //as Responses object is mandatory
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.setDescription(ProtoToOpenAPIConstants.RESPONSE_DESCRIPTION);
    ApiResponses apiResponses = new ApiResponses();
    apiResponses.addApiResponse(ProtoToOpenAPIConstants.SUCCESS_RESPONSE_CODE, apiResponse);
    operation.setResponses(apiResponses);
    //append forward slash to preserve openAPI syntax
    openAPI.getPaths().addPathItem(ProtoToOpenAPIConstants.PATH_SEPARATOR + path, pathItem);
}
 
Example 8
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private ApiResponses createApiResponses(
        MethodDeclaration methodDeclaration) {
    ApiResponse successfulResponse = createApiSuccessfulResponse(
            methodDeclaration);
    ApiResponses responses = new ApiResponses();
    responses.addApiResponse("200", successfulResponse);
    return responses;
}
 
Example 9
Source File: SchemaGenerator.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
private static void resolveAPIResponse(String status, Type resolvedType, ApiResponses responses, Path modelsDir) {
    final Schema<?> responseSchema = processType(resolvedType, modelsDir);
    final ApiResponse response = new ApiResponse();
    final Content content = new Content();
    final MediaType mediaType = new MediaType();
    mediaType.schema(responseSchema);
    content.addMediaType("application/json", mediaType);
    response.content(content);
    response.description("Some random thing");
    responses.addApiResponse(status, response);
}
 
Example 10
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testInlineMapResponse() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    Schema schema = new Schema();
    schema.setAdditionalProperties(new StringSchema());
    schema.addExtension("x-ext", "ext-prop");

    ApiResponse apiResponse = new ApiResponse();
    apiResponse.description("it works!");
    MediaType mediaType = new MediaType();
    mediaType.setSchema(schema);

    Content content = new Content();
    content.addMediaType("*/*",mediaType);

    apiResponse.setContent(content);
    apiResponse.addExtension("x-foo", "bar");

    ApiResponses apiResponses = new ApiResponses();
    apiResponses.addApiResponse("200",apiResponse);


    openAPI.path("/foo/baz", new PathItem()
            .get(new Operation()
                    .responses(apiResponses)));


    new InlineModelResolver().flatten(openAPI);

    ApiResponse response = openAPI.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Schema property = response.getContent().get("*/*").getSchema();
    assertTrue(property.getAdditionalProperties() != null);
    assertTrue(openAPI.getComponents().getSchemas() == null);
    assertEquals(1, property.getExtensions().size());
    assertEquals("ext-prop", property.getExtensions().get("x-ext"));
}
 
Example 11
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new operation object using the URI template object
 *
 * @param resource API resource data
 * @return a new operation object using the URI template object
 */
private Operation createOperation(SwaggerData.Resource resource) {
    Operation operation = new Operation();
    populatePathParameters(operation, resource.getPath());
    updateOperationManagedInfo(resource, operation);

    ApiResponses apiResponses = new ApiResponses();
    ApiResponse apiResponse = new ApiResponse();
    apiResponse.description("OK");
    apiResponses.addApiResponse(APIConstants.SWAGGER_RESPONSE_200, apiResponse);
    operation.setResponses(apiResponses);
    return operation;
}
 
Example 12
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testInlineResponseModel() throws Exception {
    OpenAPI openAPI = new OpenAPI();


    StringSchema stringSchema1 = new StringSchema();

    ObjectSchema objectSchema1 = new ObjectSchema();
    objectSchema1.addProperties("name", stringSchema1);
    objectSchema1.addExtension("x-ext", "ext-prop");

    MediaType mediaType1 = new MediaType();
    mediaType1.setSchema(objectSchema1);

    Content content1 = new Content();
    content1.addMediaType("*/*", mediaType1 );

    ApiResponse response1= new ApiResponse();
    response1.setDescription("it works!");
    response1.setContent(content1);

    ApiResponses responses1 = new ApiResponses();
    responses1.addApiResponse("200",response1);

    Operation operation1 = new Operation();
    operation1.setResponses(responses1);

    PathItem pathItem1 = new PathItem();
    pathItem1.setGet(operation1);
    openAPI.path("/foo/bar",pathItem1);



    StringSchema stringSchema2 = new StringSchema();

    ObjectSchema objectSchema2 = new ObjectSchema();
    objectSchema2.addProperties("name", stringSchema2);
    objectSchema2.addExtension("x-ext", "ext-prop");
    MediaType mediaType2 = new MediaType();
    mediaType2.setSchema(objectSchema2);

    Content content2 = new Content();
    content2.addMediaType("*/*", mediaType2 );

    ApiResponse response2 = new ApiResponse();
    response2.setDescription("it works!");
    response2.addExtension("x-foo","bar");
    response2.setContent(content2);

    ApiResponses responses2 = new ApiResponses();
    responses2.addApiResponse("200",response2);

    Operation operation2 = new Operation();
    operation2.setResponses(responses2);

    PathItem pathItem2 = new PathItem();
    pathItem2.setGet(operation2);
    openAPI.path("/foo/baz",pathItem2);


    new InlineModelResolver().flatten(openAPI);

    Map<String, ApiResponse> responses = openAPI.getPaths().get("/foo/bar").getGet().getResponses();

    ApiResponse response = responses.get("200");
    assertNotNull(response);

    Schema schema = response.getContent().get("*/*").getSchema();
    assertTrue(schema.get$ref() != null);
    assertEquals(1, schema.getExtensions().size());
    assertEquals("ext-prop", schema.getExtensions().get("x-ext"));

    Schema model = openAPI.getComponents().getSchemas().get("inline_response_200");
    assertTrue(model.getProperties().size() == 1);
    assertNotNull(model.getProperties().get("name"));
    assertTrue(model.getProperties().get("name") instanceof StringSchema);
}
 
Example 13
Source File: SwaggerConverter.java    From raptor with Apache License 2.0 3 votes vote down vote up
/**
 * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#responsesObject
 *
 * @return
 */
protected ApiResponses getApiResponses(Rpc rpc) {
    ApiResponses apiResponses = new ApiResponses();

    apiResponses.addApiResponse("200", getSuccessApiResponse(rpc));

    return apiResponses;

}
 
Example 14
Source File: InlineModelResolverTest.java    From swagger-parser with Apache License 2.0 2 votes vote down vote up
@Test
public void testInlineResponseModelWithTitle() throws Exception {
    OpenAPI openAPI = new OpenAPI();

    String responseTitle = "GetBarResponse";

    StringSchema stringSchema1 = new StringSchema();

    ObjectSchema objectSchema1 = new ObjectSchema();
    objectSchema1.setTitle(responseTitle);
    objectSchema1.addProperties("name", stringSchema1);


    MediaType mediaType1 = new MediaType();
    mediaType1.setSchema(objectSchema1);

    Content content1 = new Content();
    content1.addMediaType("*/*", mediaType1 );

    ApiResponse response1= new ApiResponse();
    response1.setDescription("it works!");
    response1.setContent(content1);

    ApiResponses responses1 = new ApiResponses();
    responses1.addApiResponse("200",response1);

    Operation operation1 = new Operation();
    operation1.setResponses(responses1);

    PathItem pathItem1 = new PathItem();
    pathItem1.setGet(operation1);
    openAPI.path("/foo/bar",pathItem1);



    StringSchema stringSchema2 = new StringSchema();

    ObjectSchema objectSchema2 = new ObjectSchema();
    objectSchema2.addProperties("name", stringSchema2);
    objectSchema2.addExtension("x-foo", "bar");

    MediaType mediaType2 = new MediaType();
    mediaType2.setSchema(objectSchema2);

    Content content2 = new Content();
    content2.addMediaType("*/*", mediaType2 );

    ApiResponse response2 = new ApiResponse();
    response2.setDescription("it works!");

    response2.setContent(content2);

    ApiResponses responses2 = new ApiResponses();
    responses2.addApiResponse("200",response2);

    Operation operation2 = new Operation();
    operation2.setResponses(responses2);

    PathItem pathItem2 = new PathItem();
    pathItem2.setGet(operation2);
    openAPI.path("/foo/baz",pathItem2);



    new InlineModelResolver().flatten(openAPI);

    Map<String, ApiResponse> responses = openAPI.getPaths().get("/foo/bar").getGet().getResponses();

    ApiResponse response = responses.get("200");
    assertNotNull(response);
    assertTrue(response.getContent().get("*/*").getSchema().get$ref() != null );

    Schema model = openAPI.getComponents().getSchemas().get(responseTitle);
    assertTrue(model.getProperties().size() == 1);
    assertNotNull(model.getProperties().get("name"));
    assertTrue(model.getProperties().get("name") instanceof StringSchema);
}