Spring controller generated by Swagger is receiving NULL values in the body parameter of a POST request

I've encountered an issue with my API-first swagger client/server setup where POST request body parameters are not being transferred correctly. The Spring (4.3.14.RELEASE) server is receiving null values in the @RequestBody parameter of the POST request.

The discrepancy lies in how requests are sent over SwaggerUI versus a generated typescript client. SwaggerUI passes object fields as query parameters, which Spring handles properly, while the typescript client sends data over the json body resulting in null values on the server side.

It appears that the autogenerated client is sending parameters in the body, whereas the autogenerated server expects them in the query.

The snippet from the Swagger specifications:

/project:
    post:
      security:
      - Bearer: []
      tags:
      - Project
      summary: Create new project
      operationId: createProject
      consumes:
      - "application/json"
      - "text/json"
      parameters:
        - name: project
          in: body
          description: project value
          schema:
            $ref: '#/definitions/ProjectRequestDTO'
      responses:
          '200':
              description: Successful response
              schema:
                $ref: '#/definitions/ProjectDTO'
          default:
            description: Bad requst

The resulting Spring MVC method is defined as follows:

ApiOperation(value = "Create new project", nickname = "createHachathon", notes = "", response = ProjectDTO.class, authorizations = {
    @Authorization(value = "Bearer")
}, tags={ "Project", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Successful response", response = ProjectDTO.class),
    @ApiResponse(code = 200, message = "Bad requst") })
@RequestMapping(value = "/project",
    consumes = { "application/json", "text/json" },
    method = RequestMethod.POST)
default ResponseEntity<ProjectDTO> createHachathon(@ApiParam(value = "project value"  )  @Valid @RequestBody ProjectRequestDTO project) {

When I send a request from typescript using a manually modified client (added title parameter for demonstration purposes), it looks like this:

return this.httpClient.post<ProjectDTO>(`${this.basePath}/project?title=hello`,

In the Chrome console, the resulting request is displayed as shown here: https://i.sstatic.net/ZzID4.png

Unfortunately, Spring only receives the values passed via query parameters and not those sent through the request body:

https://i.sstatic.net/EdY4F.png

Please assist me in resolving this issue to ensure that my swagger-codegen-maven-plugin 2.3.1 generates a client/server swagger API that transfers data seamlessly.

Answer №1

The main issue stems from Spring disregarding method parameter annotations found in the implemented Interface, causing the @RequestBody annotation to be overlooked in my Controller implementation.

By setting the

<delegatePattern>true</delegatePattern>
parameter within the <configOptions> section of the swagger-codegen-maven-plugin, I was able to resolve this issue.

This parameter prompts Swagger to create invocations of delegate methods within the default implementation of API Interface methods. By having my Controller implement and override these delegate methods, the original source method annotations remain intact.

Answer №2

Apologies for the delay in response. I hope this information proves useful to someone out there. I encountered a similar issue while working with spring boot+Swagger2. In my REST API, specifically with the POST method:

public void getAllNames(@ApiParam(name = "Get All names Request",
            value = "Request to get all names",
            required = true) @RequestBody BasicCredentialsJsonObject requestJson)

To resolve the problem, I had to add Json annotations (JsonPropertyOrder, JsonProperty) to the following class. It was only after making these changes that the issue was resolved.

BasicCredentialsJsonObject :

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "password",
    "username"
})
public class BasicCredentialsJsonObject {

    @JsonProperty("username")
    private String username;

    @JsonProperty("password")
    private String password;
}

Answer №3

There are times when even the smallest things can cause problems, like my request body being null in the controller. I realized that the issue was caused by an incorrect import - instead of using the swagger.requestBody package, I should have been importing from springframeWork.request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty with Ionic: unable to compile for android

I am currently working on an Ionic 3.4 project and trying to build it for Android testing. Following the installation of Android Studio, the Android SDK, and Java 8, I proceeded with the command: ionic cordova platform add android However, when I atte ...

Is there a way to `npm link` a typescript dependency that has peer dependencies?

In the midst of working on my React/Redux typescript project A, my team and I decided to streamline our process by extracting some of the React components and Redux code into a separate NPM module. This led me to create another React/Redux TS project B. I ...

The string variable in the parent app is resetting to empty after being populated by the service call

I am facing an issue with my app components where AppComponent acts as the parent and ConfigComponent as the child. In the constructor of AppComponent, a service call is made to set a variable but I encounter unexpected behavior when trying to access this ...

Error TS 2322 - The property 'id' is not present in the object of type '{ id: number'

Just starting out with Angular and TypeScript. I created a model with the same properties but encountered an error and am struggling to find a solution: TS2322: Type '{ id: number; model: string; plate: string; deliveryDate: string; deadline: st ...

Getting the value from an array of objects in React Redux Toolkit

Task: const postsData = useSelector((state: RootState) => state.postsSlice.posts); { postsData?.map((post) => { return ( <PostCard key={post.id} title={post.title} description={post.body} user={post.use ...

Angular encountered an issue while attempting to differentiate '[object Object]'. The permissible types for differentiation are limited to arrays and iterables

I need help iterating through an Object received from a service call and displaying it in a table using *ngFor. Unfortunately, I encounter the following error during this process: Error trying to diff '[object Object]'. Only arrays and iterables ...

Encountering 'null' error in template with Angular 4.1.0 and strictNullChecks mode

After updating Angular to version 4.1.0 and activating "strictNullChecks" in my project, I am encountering numerous errors in the templates (.html) that look like this: An object may be 'null' All these errors are pointing to .html templat ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

How can folder permissions be set for a user in Sharepoint 2013 using Rest API from .Net, but without requiring a Sharepoint environment

Is there a way to adjust folder permissions for a user in Sharepoint 2013 utilizing Rest API from .Net without the need for a Sharepoint environment? ...

Basic Karma setup with Typescript - Error: x is undefined

I am trying to configure a basic test runner using Karma in order to test a TypeScript class. However, when I attempt to run the tests with karma start, I encounter an error stating that ReferenceError: Calculator is not defined. It seems like either the ...

The CoreUI Sidebar gracefully hovers over the main page content

I recently started using CoreUI to design the layout for my application, but I ran into an issue while trying to integrate the Sidebar. Although the Sidebar is visible on the left side, I'm having trouble making sure that the router-view takes up the ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

When attempting to navigate to the index page in Angular, I encounter difficulties when using the back button

I recently encountered an issue with my Angular project. On the main index page, I have buttons that direct me to another page. However, when I try to navigate back to the index page by clicking the browser's back button, I only see a white page inste ...

Developing Angular applications with numerous projects and libraries in the build process

The other day I successfully deployed the initial version of our front-end application, but encountered some confusion during the build process setup. Many Angular apps do not utilize the workspace feature unless they are creating multiple standalone appli ...

How can one change the data type specified in an interface in TypeScript?

I am currently diving into TypeScript and looking to integrate it into my React Native application. Imagine having a component structured like this: interface Props { name: string; onChangeText: (args: { name: string; value: string }) => void; s ...

react-query: QueryOptions not functioning as expected when utilizing userQueries()

When passing certain "query options" while using useQueries() to fetch multiple queries simultaneously, these specified "query options" do not get applied during query executions (e.g. refetchOnWindowFocus has a value of true but I want it to be false). F ...

Export problem in TypeScript

I'm having trouble with exporting in the prisma TypeScript file while executing it within a Node.js GraphQL project. Here is the error I am encountering: 05-12-2018 18:20:16: SyntaxError: /home/user/Publish/PracticeBusiness/src/generated/prisma.ts: ...

Tips on preventing the copying of .txt and .xml files with the fs-extra.copySync function

Currently, I am working on a small TypeScript assignment and facing an issue that I can't seem to solve. Any guidance or advice on the problem mentioned below would be greatly appreciated. The task at hand involves copying a directory from one locati ...

Determine percentage and classification using a pair of functions

My goal is to display the level as a number along with a progress bar that ranges from 0 to 99 based on the current level. After researching online, I came across a math formula for leveling which is: constant * Math.sqrt(xp); In order to achieve this, I ...

Error 404 occurred when attempting to use the DELETE method with Spring MVC and

Can anyone help me understand this issue? Everything is working fine, except for one method that isn't functioning and keeps giving a 404 error. I have a couple of requests function deleteFunc(id) { $.ajax({ dataType: "js ...