rest api – My swagger is broken – FAILED TO LOAD API DEFINITION

I’m sure It’s likely improper comments on some interface files on custom modules. But my question is … is there an easy way to search (grep) on the server or other command line type ways to find where the issue might reside?

undefined https://website.com/rest/all/schema?services=all

I haven’t tried it yet prior to typing this up but I’m assuming it may provide more error detail on the page’s GET /rest/1/schema?services=all AJAX request.

certificado – Uso do swagger no mac

Estou seguindo um tutorial para a criacao de uma api com dotnet core, e estou com o seguinte problema: Ao utilizar o comando dotnet dev-certs https –trust eu deveria estar habilitado a usar o swagger, mas tenho a seguinte resposta no console:
inserir a descrição da imagem aqui

Quanto uso https://localhost:5001/swagger o servidor nao carrega. Como posso corrigir isso?

¿Por qué Swagger muestra error: “should NOT have additional properties”?

Estoy aprendiendo y practicando con Swagger. Al definir los parámetros para una ruta, me muestra el siguiente error:

Structural error at paths./autores/{id}/books/{idBook}.get.parameters.0
should NOT have additional properties additionalProperty: descrption

Tengo definido otro endpoint similar uno arroja este error, sí en este path en particular. Dejo el código a continuación. El error, como informa Swagger, está en los parameters del get de:

"/autores/{id}/books/{idBook}"

Leí que los path params debían ser requeridos pero sigue sin solucionarse.

openapi: 3.0.0
servers:
  - description: ServidorLocal
    url: 'http://localhost:3000'
info:
  version: 1.0.0
  title: Aplicacion de Escritores
  description: Documentación API Escritores
  contact: 
    name: Franco Fernandez
    email: fran.fercalderon@gmail.com
paths:
  /autores:
    get:
      tags:
        - Autores
      summary: Obtener listado de todos los autores.
      responses:
        '200':
          description: Listado de autores.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Escritores'
  '/autores/{id}/books':
    get:
      summary: Bibliografía de un autor especifico
      tags:
        - Libros
      parameters:
        - name: id
          in: path
          required: true
          description: Id unico del autor
          schema:
            type: string
      responses:
        '200':
          $ref: '#/components/schemas/Book'
        '404':
          description: Autor inexistente
  '/autores/{id}/books/{idBook}':
    get:
      summary: Obtener libro en específico
      tags:
        - Libros
      parameters:
        - name: idBook
          in: path
          required: true
          descrption: id del libro
          schema:
            type: integer
            format: int32
        - name: id
          in: path
          required: true
          descrption: id del autor
          schema:
            type: integer
            format: int32
      responses:
        '200':
          $ref: '#/components/schemas/Book'
        '404':
          description: Libro inexistente
components:
  schemas:
    Escritores:
      type: object
      required:
        - name
        - lastname
      properties:
        id:
          type: integer
          format: int64
          example: 1
        name:
          type: string
          example: Joanne K 
        lastname:
          type: string
          example: Rowling
        dob:
          type: string
          format: date
          example: 04/09/1981
        books:
          type: array
          items:
            $ref: '#/components/schemas/Book'
    Book:
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 1
        title:
          type: string
          example: Harry Potter 
        description:
          type: string
          example: Fantasy Book
        publishYear:
          type: integer
          format: int64 
          example: 1998        

java – What is the better way to save swagger code gen plugin generated model classes in spring boot maven application?

So, I am working on a spring boot maven project in Eclipse IDE. And here is my pom.xml.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-swagger-codegen-api-client</artifactId>
    <name>spring-swagger-codegen-api-client</name>
    <packaging>jar</packaging>
    <url>https://github.com/swagger-api/swagger-codegen</url>
    <description>Swagger Java</description>
...
...ommited for brevity
...

    <build>
        <plugins>

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.3.1</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/customer-data-v2.json</inputSpec>
                <language>java</language>
                <configOptions>
                   <sourceFolder>swagger</sourceFolder>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>
        </plugins>
    </build>

</project>

So when I compile the project using mvn compile it executes swagger code gen plugin and outputs all the generated classes to swagger folder under target folder.

And I am using swagger code gen plugin to generate all the model classes using the customer json schema which it currently outputs to swagger sub folder under target folder.

So I know that I can keep all the generated classes under target folder itself as maven executes swagger plugin before compiling the actual source code. So right now there is no issue with it.

But all the generated classes are Model classes which are used for processing request and response data. So currently there is no issue in doing so, but in future we might add additional functionality which might require updates to generated model classes and may be difficult to update them from target folder.

So my main question is should I move all the generated pojo classes to something like src/main/org/**/* folder or keep the model classes inside target folder itself? What is the better approach including other alternative?

Should I use swagger on all REST APIs?

Yes, in general you should just the documentation tool cover the entire API. Having exceptions means you then need to maintain all of those exceptions, and humans are prone to error.

If you’re worried about data pollution then you should actually secure your endpoints. Hiding them will not stop a dedicated attacker.

If you’re worried that specialized one-off endpoints aren’t useful, you should reconsider having weird special cases in the same API as your public endpoints.

go – Swagger api with Gorm db connection

I have an API Swagger generated, I’m not satisfied with how I’m handling my part of the contract e.g. how I have constructed my db and handlers modules.
Specially how I’m dealing the the database connection, can this not be made more robust by using interfaces. For simplicity I’m just including one implemented endpoint.

// This file is safe to edit. Once it exists it will not be overwritten

package restapi

import (
    "crypto/tls"
    "net/http"

    "github.com/go-openapi/errors"
    "github.com/go-openapi/runtime"
    "github.com/go-openapi/runtime/middleware"
    log "github.com/sirupsen/logrus"
    "hairdoo.com/m/v2/handlers"
    "hairdoo.com/m/v2/models"
    "hairdoo.com/m/v2/restapi/operations"
    "hairdoo.com/m/v2/restapi/operations/company"
    "hairdoo.com/m/v2/restapi/operations/employee"
)

//go:generate swagger generate server --target ../../hairdoo --name Hairdoo --spec ../swagger.yml --principal interface{}

//var db *gorm.DB

func init() {
    // Log as JSON instead of the default ASCII formatter.
    /*log.SetFormatter(&log.JSONFormatter{
        TimestampFormat: "2006-01-02 15:04:05",
        //PrettyPrint:     true,
    })*/

    // Output to stdout instead of the default stderr
    // Can be any io.Writer, see below for File example
    //log.SetOutput(os.Stdout)

    log.SetFormatter(&log.TextFormatter{
        DisableColors: false,
        FullTimestamp: true,
    })

    // Only log the warning severity or above.
    //log.SetLevel(log.WarnLevel)
    log.SetLevel(log.InfoLevel)
}

func configureFlags(api *operations.HairdooAPI) {
    // api.CommandLineOptionsGroups = ()swag.CommandLineOptionsGroup{ ... }
}

func configureAPI(api *operations.HairdooAPI) http.Handler {
    // configure the api here
    api.ServeError = errors.ServeError

    // Set your custom logger if needed. Default one is log.Printf
    // Expected interface func(string, ...interface{})
    //
    // Example:
    //api.Logger = log.Printf

    api.UseSwaggerUI()
    // To continue using redoc as your UI, uncomment the following line
    // api.UseRedoc()

    api.JSONConsumer = runtime.JSONConsumer()
    //api.UrlformConsumer = runtime.DiscardConsumer

    api.JSONProducer = runtime.JSONProducer()

    api.CompanyAddCompanyHandler = company.AddCompanyHandlerFunc(func(params company.AddCompanyParams) middleware.Responder {
        //log.Debugf("Add commpay Handler Called")
        //log.Infof("Payload Data : %v", params.Body)

        response, err := handlers.AddCompany(params)
        if err != nil {
            return company.NewAddCompanyBadRequest().WithPayload(&models.ErrorReponse400{
                Error: err.Error(),
            })
        }

        return company.NewAddCompanyCreated().WithPayload(response)
    })

handlers/company.go

package handlers

import (
    "hairdoo.com/m/v2/db"
    "hairdoo.com/m/v2/models"
    "hairdoo.com/m/v2/restapi/operations/company"
)

func AddCompany(params company.AddCompanyParams) (*models.Company, error) {
    result, err := db.AddCompany(params.Body)
    if err != nil {
        return nil, err
    }

    return result, nil
}

db/company.go

import (
    "fmt"
    "time"

    "gorm.io/gorm"
    "hairdoo.com/m/v2/models"
)

type Company struct {
    gorm.Model
    Name           string `gorm:"uniqueIndex"`
    Phone          string
    Email          string
    ContatctPerson string
    CategoryID     int
    Category       *Category
    Status         string
}

type Category struct {
    ID   int
    Name string `gorm:"uniqueIndex"`
}

func AddCompany(companyObj *models.Company) (*models.Company, error) {
    db := Open()
    var result *gorm.DB

    category := &Category{}

    db.Where("name = ?", companyObj.Category.Name).First(category)

    company := convertToDBCompany(companyObj, false)
    if category.ID != 0 {
        result = db.Exec("INSERT INTO companies (created_at, updated_at, name, phone, email, contatct_person, category_id) values (?, ?, ?, ?, ?, ?, ?);",
            time.Now(), time.Now(), companyObj.Name, companyObj.Phone, companyObj.Email, companyObj.ContatctPerson, category.ID)
    } else {
        result = db.Create(company)
    }

    if result.RowsAffected < 1 {
        return nil, result.Error
    }

    // add employee to db if object present
    var employees ()*models.EmployeeItems0
    if companyObj.Employee != nil {
        for _, employeeInput := range companyObj.Employee {
            result, err := AddEmployee(employeeInput)
            if err != nil {
                return nil, err
            }
            employees = append(employees, result)
        }
    }

    return convertToModelCompany(company, employees), nil
}

database.go

package db

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func Open() *gorm.DB {
    connString := "root:12345@tcp(0.0.0.0:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(connString), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(Company{}, Category{}, Employee{})

    return db
}
````

Swagger not loading – 500 error: “message”:”Internal Error. URL.com/rest/all/schema

Found a couple error log entries that may be causing it. But I don’t read log files very well. I can’t find much on Swagger issues. Could it be the setup of Magento on my host?

500 : {“message”:”Internal Error. Details are available in Magento log file.

[2020-12-02 02:23:48] main.DEBUG: cache_invalidate: {“method”:”POST”,”url”:”http://www.URL.com/admin/admin/index/index/key/6c558b5736cfb18795d1767a283cd2e99f669b3466dbb0d08ec8a1cada22b244/”,”invalidateInfo”:{“tags”:[“BACKEND_MAINMENU”],”mode”:”matchingAnyTag”},”is_exception”:false} []
[2020-12-02 02:37:08] main.DEBUG: cache_invalidate: {“method”:”POST”,”url”:”http://www.URL.com/admin/admin/system_config/save/key/ada8eb815031f0e8fdee95f3923a54f41b2b4a5a99b544465fc84d77d0b3ae61/section/webapi/”,”invalidateInfo”:{“tags”:[“config_scopes”,”CONFIG”],”mode”:”matchingTag”},”is_exception”:false} []

I had just created an API key when I got this error last night. Flushed cache and went to bed. This AM, still seeing it.

Change the Swagger header used by the access token to something other than Authorize

By default, Swagger-UI OAuth2 will send the access token in the Authorize header (as a Bearer token).

I need to find a way to get Swagger to put that in a different header name besides Authorize.

Details:

In the end, I need to send both the Access Token and the ID Token. While Swagger can send either one, unfortunately it seems to be hard coded to put them in the Authorize header. I need to find a way to put one of them in a different header.

magento2 – Magento 2 swagger error

while accessing https://website-url/swagger got error as

500 : {“message”:”Internal Error. Details are available in Magento log file. Report ID: webapi-5f33c4d0d4891″} https://website-url/rest/all/schema?services=all

Then I checked into exception log

(2020-08-11 11:20:13) main.CRITICAL: Report ID: webapi-5f327eeda2f5a; Message: Class “decimal” does not exist. Please note that namespace must be specified. {“exception”:”(object) (Exception(code: 0): Report ID: webapi-5f327eeda2f5a; Message: Class “decimal” does not exist. Please note that namespace must be specified. at /var/www/html/website/vendor/magento/framework/Webapi/ErrorProcessor.php:205, LogicException(code: 0): Class “decimal” does not exist. Please note that namespace must be specified. at /var/www/html/website/vendor/magento/framework/Reflection/TypeProcessor.php:139)”} ()

Como gerar o Swagger UI em português com Asp Net Core 3.1

Obrigado por contribuir com o Stack Overflow em Português!

  • Certifique-se de responder à pergunta. Entre em detalhes sobre a sua solução e compartilhe o que você descobriu.

Mas evite

  • Pedir esclarecimentos ou detalhes sobre outras respostas.
  • Fazer afirmações baseadas apenas na sua opinião; aponte referências ou experiências anteriores.

Para aprender mais, veja nossas dicas sobre como escrever boas respostas.