Search code examples
javascriptswagger

400 Validation error when I try to post with swagger


I made a project with swagger only for testing swagger and I get a 400 bad When I try to post what is wrong??

I do not have any problem geting the data from the array.

{
    "message": "Validation errors",
    "errors": [
        {
            "code": "INVALID_REQUEST_PARAMETER",
            "errors": [
                {
                    "code": "REQUIRED",
                    "message": "Value is required but was not provided",
                    "path": [
                        "paths",
                        "/recipe",
                        "post",
                        "parameters",
                        "0"
                    ]
                }
            ],
            "in": "body",
            "message": "Invalid parameter (body): Value is required but was not provided",
            "name": "body",
            "path": [
                "paths",
                "/recipe",
                "post",
                "parameters",
                "0"
            ]
        }
    ]
}

recipe.js file:

module.exports.createRecipe = (req, res) => {
  let newRecipe = req.body;
  newRecipe.id = recipeList.length;
  newRecipe.isPublic = true;
  recipeList.push(newRecipe);

  return res.status(204).end();
};
paths:
  /recipe:
    x-swagger-router-controller: repice
    get:
      description: Return all the recipes
      operationId: getAllRecipes
      responses:
        200:
          description: Success get all the recipes
          schema:
            type: array
            items:
              $ref: "#/definitions/Recipe"
        500:
          description: Unexpected Error
          schema:
            type: object
            properties:
              messeage:
                type: string
    post:
      description: Create one new Recipe
      operationId: postRecipes
      parameters:
        - in: body
          name: body
          description: The recipe to be added
          required: true
          schema:
            $ref: "#/definitions/Recipe"

      responses:
        204:
          description: Success adding the rescipe
        500:
          description: Unexpected Error
          schema:
            type: object
            properties:
              messeage:
                type: string

What Do I need to do to make it work???

What do I need to do to make

I expect a 204 request and the recipe will be added to the array


Solution

  • I need to learn how to use Swagger to document my code and I thought to learn from Node JS: API Development with Swagger in Udemy.com but I had a problem with getting the params from req.swagger.params.id.value for example and req.body

    to fix the problem with the body I found out that you needed to add app.use(bodyParser.json()); in the app.js file but when I did this I could not the req.swagger.params.id.value to work.

        "use strict";
    
    var dotenv = require("dotenv");
    var app = require("connect")();
    var http = require("http");
    var swaggerTools = require("swagger-tools");
    var swaggerUI = require("swagger-ui-express");
    var serverPort = process.env.PORT || 10010;
    var bodyParser = require("body-parser");
    
    dotenv.config();
    var options = {
      controllers: "./api/controllers",
      useStubs: process.env.NODE_ENV === "development" ? true : false, // Conditionally turn on stubs (mock mode)
    };
    
    var swaggerDoc = require("./api/swagger/swagger.json");
    
    app.use(bodyParser.json());
    app.use(
      bodyParser.urlencoded({
        extended: false,
      })
    );
    // Initialize the Swagger middleware
    swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
      // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
      app.use(middleware.swaggerMetadata());
    
      // Validate Swagger requests
      app.use(middleware.swaggerValidator());
    
      // Route validated requests to appropriate controller
      app.use(middleware.swaggerRouter(options));
    
      // Serve the Swagger documents and Swagger UI
      app.use(middleware.swaggerUi());
    
      app.use("/docs", swaggerUI.serve, swaggerUI.setup(swaggerDoc));
    
      // Start the server
      http.createServer(app).listen(serverPort, function () {
        console.log(
          "Your server is listening on port %d (http://localhost:%d)",
          serverPort,
          serverPort
        );
      });
    });
    

    I started to look at this example to see how they have set up Swagger

    https://github.com/apigee-127/swagger-tools/blob/master/examples/2.0/index.js

    with this example, I can get both parameters. But

    And add this to make a page with the documentation for your AP: app.use("/docs", swaggerUI.serve, swaggerUI.setup(swaggerDoc));

    To get the response from the api remember you need to put the right address in postman and for example:

    http://127.0.0.1:10010/v1/api/recipe

    and in the controlles folder file .js you need to add this in the bottom of the methode get method:

     res.setHeader("Content-Type", "application/json");
     res.end(JSON.stringify(List));
    

    create method:

     res.setHeader("Content-Type", "application/json");
     res.statusCode =201; 
     res.end(JSON.stringify(newRecipe));
    

    make a error:

    res.setHeader("Content-Type", "application/json");
    res.statusCode = 404;
    res.end(`Could not find the recipe with id: ${recipeId}`);