Swagger definition errors - jax-rs

Trying to use Swagger on my JAX-RS application with enunciate Maven plugin.
The generated JSON definition works well.
But when I try to validate it online with Swagger Editor, the converted YAML file has some weird errors.
For example:
Definition:
parameters:
- name: body
in: body
type: file
description: 'Bla bla'
responses:
'201':
ERROR:
Parameters with "type: file" must have "in: formData"
JAX-RS Code:
#POST
#Path(value = "/validatedata")
public Response validate(ValidateDataFromInput validateDataFromInput) throws CustomException {
return Response.status(Status.ACCEPTED).entity(validationActionService.getDataFromInput(validateDataFromInput.getConsumerInput(),
validateDataFromInput.getValidateInput(), null)).build();
}
I am using: swagger-core-1.5.21 and enunciate-maven-plugin-2.11.1.
Not sure which is wrong here.

Related

oas3 kotlin codegenerator: using multipart/form-data and free-form JSON object in the same request

I'm using OAS3 codegenerator to create Kotlin server code for a request containing both a file-upload, and a free-form json object that can contain arbitrary values. According to the swagger documentation, I should be able to create a free-form object that using type: object and additionalProperties : true.
However if I edit the upload photos endpoint in modules/openapi-generator/src/test/resources/3_0/petstore.yaml in the oas3 codegen samples like this
requestBody:
content:
multipart/form-data:
schema:
properties:
file:
description: file to upload
type: string
format: binary
additionalMetadata:
description: Additional data to pass to server
type: object <-- CHANGED FROM STRING
additionalProperties: true <-- ADDED
and run ./bin/generate-samples.sh ./bin/configs/kotlin-server-jaxrs-spec.yaml
the additionalMetadata field is dropped from PetApi
#POST
#Consumes("multipart/form-data")
#Produces("application/json")
suspend fun uploadFile(#PathParam("petId") petId: kotlin.Long, #FormParam(value = "file") fileInputStream: InputStream?): Response {
Is there a problem with how I'm specifying the request?

How to show input and output exemple with nelmio-api-bundle and php8.1

I'm currently trying to make an API doc page thanks to nelmio-api-bundle. I only have one route which is a POST route. I'm receiving a JSON in the body of the request and I'm using the Serializer from symfony to deserialize it in a DTO. I'm also using a DTO for the response (which contains the status code, a bool set to true or false, and a message). Now I'm trying to use these DTO (for input and output) to build the API documentation with nelmio-api-bundle but how to make it ? I'm using PHP8.1 attributes to make it, for response it almost works (except that the response is shows as an array) but I don't know how to make it for the inputs.
Here is my current code:
#[Route('/user', methods: ['POST'])]
#[OA\Parameter(
name: 'user',
description: 'The user information in JSON',
in: 'query',
required: true
)]
#[OA\Response(
response: 200,
description: 'Returns the success response',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: SuccessResponseDTO::class))
)
)]
public function registerUser(Request $request, LoggerInterface $logger): JsonResponse
{
//the code to register the user
}
And here is the result:
Do someone know how to make it ?

Correct media type for swagger spec for downloading zip file

I am creating an api which allows downloading a zip file, so for this I am looking for correct media type for sending this zip file as response in swagger "2.0" specification.
My current api spec looks like this
/config:
get:
produces:
- application/zip
responses:
200: # OK
description: All config files
schema:
type: string
format: binary
I have compiled this spec with "go-swagger" and implemented the backend for this, but when try to call this API I get this error
http: panic serving 127.0.0.1:20366: applicationZip producer has not yet been implemented
In the documentation of swagger I don't see this media type
Official swagger media types
So then what should be the correct media type if we want to provide an API to download a zip file.
Thanks in advance
You need to implement this.
The error occurs because of the following generated code:
func NewSampleAPI(spec *loads.Document) *SampleAPI {
return &SampleAPI{
...
ApplicationZipProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error {
return errors.NotImplemented("applicationZip producer has not yet been implemented")
}),
So after calling NewSampleAPI, you should set ApplicationZipProducer:
api := operations.NewSampleAPI(swaggerSpec)
api.ApplicationZipProducer = func(w io.Writer, data interface{}) error {
...
}
You should use "application/octet-stream" for implementing api that downloads file as an attachment , and since its Producer is already implemented by default so you won't face this issue.
As mentioned in other answer, using "application/octet-stream" partially solves the issue, but the browser does not know the file format. I think that his can be improved adding the correct headers to the response, that will tell the browser that the file has a zip extension. At least, I can download a file as ZIP and Firefox recognizes it.
#Operation(summary = "Downloads a ZIP file)
#GetMapping(value = "/zip", produces="application/octet-stream")
public byte[] start(HttpServletResponse response) {
final ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
.filename("MyFile.zip").build();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
return getZipDataAsByteArray();
}

RESTEASY003145: Unable to find a MessageBodyReader of content-type text/xml;charset=UTF-8

I'm a newbie in a REST services, but all solutions I found was due to lack of necessary providers.
Dependencies:
compile group: 'org.jboss.resteasy', name: 'resteasy-client', version: '3.6.1.Final'
compile group: 'org.jboss.resteasy', name: 'resteasy-jackson2-provider', version: '3.6.1.Final'
compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.+"
compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.+"
Data class:
#JacksonXmlRootElement(localName = "Response")
data class ResponseSessionInit(#JacksonXmlProperty(localName = "Error") val error: Error)
data class Error(#JacksonXmlProperty(localName = "Text", isAttribute = true) val text: String)
Proxy:
interface L3Client {
#POST
#Consumes("text/xml;charset=UTF-8")
#Produces("text/xml; charset=UTF-8")
fun test(string: String): ResponseSessionInit
}
Proxy method invocation:
val proxy = client.target(API).proxyBuilder(L3Client::class.java).build()
println(proxy.test("<Request><ProtocolInfoGet/></Request>"))
I receive exception:
javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type text/xml;charset=UTF-8 and type class ru.abinet.commons.cft.L3.messages.ResponseSessionInit
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:156)
at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.BodyEntityExtractor.extractEntity(BodyEntityExtractor.java:60)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:150)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
at com.sun.proxy.$Proxy19.test(Unknown Source)
It really looks like if Resteasy client can't find a decoder for my XML, however I have it in path.
I can change test() method to return String and successfully parse XML with something like
val mapper = XmlMapper()
mapper.registerModule(KotlinModule())
val value = mapper.readValue(xml, ResponseSessionInit::class.java)
However, I'd like to do it automagically. What I'm missing ?
Reasteasy can't handle application/xml content-type out of the box with jackson-xml. So the idea is to write it by yourself.
#Provider
#Consumes(MediaType.TEXT_XML, MediaType.APPLICATION_XML)
class BodyReaderProvider : MessageBodyReader<Any> {
//jackson instantiation and some check code here
}
and register it
val client = ResteasyClientBuilder.newBuilder()
.register(BodyReaderProvider())

Symfony - No Extension Is Able To Load The Configuration (Subscriber/Event Listening) (REST API Exception Handling with JSON output)

Purpose
Hello, I am fairly new to Symfony and am trying to create an exception/error handling functionality for our Web API.
Requirements
When a user makes an invalid request to our API, we want to return a simple JSON object that looks something like the following:
{"errorCode": 1234567, "errorMessage": "Parameter 1 is invalid. String expected"}
In addition to API-specific errors, we also want to hook into the built-in exception-handling in Symfony and re-use that, but instead of returning an HTML error page (which is what happens by default), we want to return a JSON object like:
{"errorCode": 404, "errorMessage": "Not found"}
Current Approach
Obviously, we want this to be implemented in the most efficient way, so after doing some research, I found what I think is a great approach which I can then adapt to our specific needs. Here is the tutorial I followed:
https://knpuniversity.com/screencast/symfony-rest2
I ended up buying this course in order to get access to the full code. The issue is that it was written for Symfony 2, but we are running Symfony 3.3, so some things are outdated and I have not been able to get the example running yet.
Code
So, I have posted some of the relevant code below. (I obviously cannot post the whole code, but have posted what are hopefully the relevant portions of the publicly-available code).
services.yml (Their version, Symfony 2 Style)
api_exception_subscriber:
class: AppBundle\EventListener\ApiExceptionSubscriber
arguments: []
tags:
- { name: kernel.event_subscriber }
services.yml (my full file with all comments removed)
This includes a modified version of what they have above (hopefully this is the correct Symfony 3.3 way of doing things).
NOTE: Anything that was part of the private code which I cannot show, I have replaced with the word "something".
parameters:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
AppBundle\EventListener\ApiExceptionSubscriber:
arguments:
- ['%something.something%']
tags:
- {name: 'kernel.event_subscriber'}
routing.yml (relevant section of their file)
app_api:
resource: "#AppBundle/Controller/Api"
type: annotation
defaults:
_format: json
routing.yml (my full file) - NOTE: I had to add the "_format: json" directly to the "app" section here rather than "app_api" because in our REST API, all of our URLs are at the root level, and do NOT have to be prefixed with "api" like http://localhost/api/someMethod/someMethodParameter as in the tutorial's code
app:
resource: '#AppBundle/Controller/'
type: annotation
defaults: {_format:json}
yml_route:
path: /yml-route
defaults:
_controller: AppBundle:Default:yml
awesome_route:
path: /awesome-route/{ic}
defaults:
_controller: AppBundle:Rest:awesomeRoute
src/AppBundle/RestController.php (edited to show just the basic structure)
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\Request;
class RestController extends Controller {
public function doSomething($id)
{
// Code to populate $result with data from database is here
return new JsonResponse($result);
}
// This file contains many different functions similar to doSomething() which retrieve the request for the API caller.
// For example, doSomething() can be accessed via http://localhost/app_dev.php/doSomething/123
}
src/AppBundle/Api/ApiProblem.php (edited to show just the basic structure)
namespace AppBundle\Api;
use Symfony\Component\HttpFoundation\Response;
class ApiProblem
{
// Code relevant to this class is in here
}
src/AppBundle/Api/ApiProblemException.php (edited to show just the basic structure)
<?php
namespace AppBundle\Api;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ApiProblemException extends HttpException
{
private $apiProblem;
public function __construct($severalParametersWhichICannotListHereBecauseCodeIsPrivate) {
// Does some stuff and then calls the parent:__construct
// Includes a getter for $apiProblem
}
}
src/AppBundle/EventListener/ApiExceptionSubscriber.php (edited to show just the basic structure)
<?php
namespace AppBundle\EventListener;
use AppBundle\Api\ApiProblem;
use AppBundle\Api\ApiProblemException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
// Code relevant to this subscriber is here
}
The Issue
I'm getting the following error when I try to run any type of command from the command-line bin/console:
C:\htdocs\projects\myproject>php bin/console debug:container
PHP Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: T
here is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscribe
r" (in C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListe
ner\ApiExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrin
e", "sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug",
"web_profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfo
ny\src\Symfony\Component\DependencyInjection\Loader\YamlFileLoader.php:644
Stack trace:
#0 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoader.php(614): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array,
'C:\\htdocs\\proje...')
#1 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoad in C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\Config\Loader\
FileLoader.php on line 179
Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: There
is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscriber" (i
n C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListener\A
piExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrine", "
sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_
profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfony\sr
c\Symfony\Component\Config\Loader\FileLoader.php on line 179
Symfony\Component\Config\Exception\FileLoaderLoadException: There is no extension able to load the con
figuration for "AppBundle\EventListener\ApiExceptionSubscriber" (in C:\htdoc
fig\services.yml). Looked for namespace "AppBundle\EventListener\ApiExceptio
work", "security", "twig", "monolog", "swiftmailer", "doctrine", "sensio_fra
arsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_profiler",
eb_server" in C:\htdocs\projects\myproject\app/config\services.yml (which is b
ocs\projects\myproject\app/config\config.yml"). in C:\htdocs\projects\myproject\
\Symfony\Component\Config\Loader\FileLoader.php on line 179
Call Stack:
1.4353 6149416 1. Symfony\Component\Debug\ErrorHandler->handleExcep
myproject\vendor\symfony\symfony\src\Symfony\Component\Debug\ErrorHandler.php:
What I've Tried
I've been debugging this for the last several days and have read many related discussions on Stack Overflow. I'm fairly new to services, subscribers, and dependency injection and I've tried editing both the routes.yml and services.yml numerous times. I was also getting some circular reference exceptions before but think I've fixed those now. I was hoping someone could please provide me with some direction and hopefully help me turn this into a working example on Symfony 3.3 that I can learn from. If you need any additional detail, please let me know.
From what I've learned, autowiring/autoconfiguring of services in Symfony 3.3 seems to be new and I think that may be impacting things but I'm not sure. I did try turning both of those settings off in services.yml though but with no luck.