Tyrique  Littel

Tyrique Littel

1601060400

Doing More With Springdoc-OpenAPI

In my last recent article we tried out a Spring Boot Open API 3-enabled REST project and explored some of its capabilities namely:

  • Automatic JSR-303 related swagger documentation.
  • How maven builds properties could be shown as project information in the swagger documentation.

In this continuation we will explore two additional Objectives namely:

  • Rendering Fully Qualified names in the generated swagger documentation.
  • Global Exception Handling Using Controller Advice and its related swagger documentation.

We are going to refer to https://spring.io/guides/gs/rest-service/ and https://springdoc.org/ like last time.

#java #tutorial #spring boot #rest api #swagger #openapi

What is GEEK

Buddha Community

Doing More With Springdoc-OpenAPI

Springdoc OpenAPI: Library for OpenAPI 3 with Spring boot

Full documentation

Introduction

The springdoc-openapi Java library helps automating the generation of API documentation using Spring Boot projects. springdoc-openapi works by examining an application at runtime to infer API semantics based on Spring configurations, class structure and various annotations.

The library automatically generates documentation in JSON/YAML and HTML formatted pages. The generated documentation can be complemented using swagger-api annotations.

This library supports:

  • OpenAPI 3
  • Spring-boot (v1 and v2)
  • JSR-303, specifically for @NotNull, @Min, @Max, and @Size.
  • Swagger-ui
  • Oauth 2

The following video introduces the Library:

This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal)

Getting Started

Library for springdoc-openapi integration with spring-boot and swagger-ui

  • Automatically deploys swagger-ui to a Spring Boot 2.x application
  • Documentation will be available in HTML format, using the official swagger-ui jars.
  • The Swagger UI page should then be available at http://server:port/context-path/swagger-ui.html and the OpenAPI description will be available at the following url for json format: http://server:port/context-path/v3/api-docs
    • server: The server name or IP
    • port: The server port
    • context-path: The context path of the application
  • Documentation can be available in yaml format as well, on the following path: /v3/api-docs.yaml
  • Add the springdoc-openapi-ui library to the list of your project dependencies (No additional configuration is needed):
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file:
# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

Spring-boot with OpenAPI Demo applications.

Source Code for Demo Applications.

Demo Spring Boot 2 Web MVC with OpenAPI 3.

Demo Spring Boot 2 WebFlux with OpenAPI 3.

Demo Spring Boot 1 Web MVC with OpenAPI 3.

Demo Spring Boot 2 WebFlux with Functional endpoints OpenAPI 3.

Demo Spring Boot 2 and Spring Hateoas with OpenAPI 3.

Branching

Integration of the library in a Spring Boot 2.x.x project without the swagger-ui:

  • Documentation will be available at the following url for json format: http://server:port/context-path/v3/api-docs
    • server: The server name or IP
    • port: The server port
    • context-path: The context path of the application
  • Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
  • Add the library to the list of your project dependencies. (No additional configuration is needed)
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-webmvc-core</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the OpenAPI documentation in Json format, add a custom springdoc property, in your spring-boot configuration file:
# /api-docs endpoint custom path
springdoc.api-docs.path=/api-docs
  • This step is optional: If you want to disable springdoc-openapi endpoints, add a custom springdoc property, in your spring-boot configuration file:
# disable api-docs
springdoc.api-docs.enabled=false

Error Handling for REST using @ControllerAdvice

To generate documentation automatically, make sure all the methods declare the HTTP Code responses using the annotation: @ResponseStatus.

Adding API Information and Security documentation

The library uses spring-boot application auto-configured packages to scan for the following annotations in spring beans: OpenAPIDefinition and Info. These annotations declare, API Information: Title, version, licence, security, servers, tags, security and externalDocs. For better performance of documentation generation, declare @OpenAPIDefinition and @SecurityScheme annotations within a Spring managed bean.

spring-webflux support with Annotated Controllers

  • Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
  • Add the library to the list of your project dependencies ( No additional configuration is needed)
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-webflux-ui</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file:
# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

The springdoc-openapi libraries are hosted on maven central repository. The artifacts can be viewed accessed at the following locations:

Releases:

Snapshots:

Acknowledgements

Download Details:
Author: springdoc
Source Code: https://github.com/springdoc/springdoc-openapi
License: Apache-2.0 License

#spring #spring-framework #spring-boot #java #openapi 

Springdoc Openapi: Library for OpenAPI 3 with Spring-boot

Introduction

The springdoc-openapi Java library helps automating the generation of API documentation using Spring Boot projects. springdoc-openapi works by examining an application at runtime to infer API semantics based on Spring configurations, class structure and various annotations.

The library automatically generates documentation in JSON/YAML and HTML formatted pages. The generated documentation can be complemented using swagger-api annotations.

This library supports:

  • OpenAPI 3
  • Spring-boot (v1 and v2)
  • JSR-303, specifically for @NotNull, @Min, @Max, and @Size.
  • Swagger-ui
  • Oauth 2

The following video introduces the Library:

This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal)

Getting Started

Library for springdoc-openapi integration with spring-boot and swagger-ui

  • Automatically deploys swagger-ui to a Spring Boot 2.x application
  • Documentation will be available in HTML format, using the official swagger-ui jars.
  • The Swagger UI page should then be available at http://server:port/context-path/swagger-ui.html and the OpenAPI description will be available at the following url for json format: http://server:port/context-path/v3/api-docs
    • server: The server name or IP
    • port: The server port
    • context-path: The context path of the application
  • Documentation can be available in yaml format as well, on the following path: /v3/api-docs.yaml
  • Add the springdoc-openapi-ui library to the list of your project dependencies (No additional configuration is needed):
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file:
# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

Spring-boot with OpenAPI Demo applications.

Source Code for Demo Applications.

Demo Spring Boot 2 Web MVC with OpenAPI 3.

Demo Spring Boot 2 WebFlux with OpenAPI 3.

Demo Spring Boot 1 Web MVC with OpenAPI 3.

Demo Spring Boot 2 WebFlux with Functional endpoints OpenAPI 3.

Demo Spring Boot 2 and Spring Hateoas with OpenAPI 3.

Branching

Integration of the library in a Spring Boot 2.x.x project without the swagger-ui:

  • Documentation will be available at the following url for json format: http://server:port/context-path/v3/api-docs
    • server: The server name or IP
    • port: The server port
    • context-path: The context path of the application
  • Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
  • Add the library to the list of your project dependencies. (No additional configuration is needed)
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-webmvc-core</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the OpenAPI documentation in Json format, add a custom springdoc property, in your spring-boot configuration file:
# /api-docs endpoint custom path
springdoc.api-docs.path=/api-docs
  • This step is optional: If you want to disable springdoc-openapi endpoints, add a custom springdoc property, in your spring-boot configuration file:
# disable api-docs
springdoc.api-docs.enabled=false

Error Handling for REST using @ControllerAdvice

To generate documentation automatically, make sure all the methods declare the HTTP Code responses using the annotation: @ResponseStatus.

Adding API Information and Security documentation

The library uses spring-boot application auto-configured packages to scan for the following annotations in spring beans: OpenAPIDefinition and Info. These annotations declare, API Information: Title, version, licence, security, servers, tags, security and externalDocs. For better performance of documentation generation, declare @OpenAPIDefinition and @SecurityScheme annotations within a Spring managed bean.

spring-webflux support with Annotated Controllers

  • Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
  • Add the library to the list of your project dependencies ( No additional configuration is needed)
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-webflux-ui</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file:
# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

The springdoc-openapi libraries are hosted on maven central repository. The artifacts can be viewed accessed at the following locations:

Acknowledgements

Download Details:
Author: springdoc
Source Code: https://github.com/springdoc/springdoc-openapi
License: Apache-2.0 License

#spring  #spring-boot  #java #openapi 

Tyrique  Littel

Tyrique Littel

1601060400

Doing More With Springdoc-OpenAPI

In my last recent article we tried out a Spring Boot Open API 3-enabled REST project and explored some of its capabilities namely:

  • Automatic JSR-303 related swagger documentation.
  • How maven builds properties could be shown as project information in the swagger documentation.

In this continuation we will explore two additional Objectives namely:

  • Rendering Fully Qualified names in the generated swagger documentation.
  • Global Exception Handling Using Controller Advice and its related swagger documentation.

We are going to refer to https://spring.io/guides/gs/rest-service/ and https://springdoc.org/ like last time.

#java #tutorial #spring boot #rest api #swagger #openapi

MicroProfile OpenAPI - Getting Started with MicroProfile

The MicroProfile OpenAPI specification is all about creating API documentation with the OpenAPI v3 standard. Watch this video to learn everything you need to know about this specification.

Β» Corresponding blog post: https://rieckpil.de/whatis-eclipse-microprofile-openapi/
Β» Source code on GitHub: https://github.com/rieckpil/getting-started-with-eclipse-microprofile
Β» More about MicroProfile: https://rieckpil.de/category/microprofile/

#openapi #microprofile openapi #microprofile

Lawrence  Lesch

Lawrence Lesch

1677103020

Trpc-openapi: OpenAPI support for tRPC

Trpc-openapi


OpenAPI support for tRPC 🧩

  • Easy REST endpoints for your tRPC procedures.
  • Perfect for incremental adoption.
  • OpenAPI version 3.0.3.

Usage

1. Install trpc-openapi.

# npm
npm install trpc-openapi
# yarn
yarn add trpc-openapi

2. Add OpenApiMeta to your tRPC instance.

import { initTRPC } from '@trpc/server';
import { OpenApiMeta } from 'trpc-openapi';

const t = initTRPC.meta<OpenApiMeta>().create(); /* πŸ‘ˆ */

3. Enable openapi support for a procedure.

export const appRouter = t.router({
  sayHello: t.procedure
    .meta({ /* πŸ‘‰ */ openapi: { method: 'GET', path: '/say-hello' } })
    .input(z.object({ name: z.string() }))
    .output(z.object({ greeting: z.string() }))
    .query(({ input }) => {
      return { greeting: `Hello ${input.name}!` };
    });
});

4. Generate an OpenAPI document.

import { generateOpenApiDocument } from 'trpc-openapi';

import { appRouter } from '../appRouter';

/* πŸ‘‡ */
export const openApiDocument = generateOpenApiDocument(appRouter, {
  title: 'tRPC OpenAPI',
  version: '1.0.0',
  baseUrl: 'http://localhost:3000',
});

5. Add an trpc-openapi handler to your app.

We currently support adapters for Express, Next.js, Serverless & Node:HTTP.

Fetch, Fastify, Nuxt, Workers & more soonβ„’, PRs are welcomed πŸ™Œ.

import http from 'http';
import { createOpenApiHttpHandler } from 'trpc-openapi';

import { appRouter } from '../appRouter';

const server = http.createServer(createOpenApiHttpHandler({ router: appRouter })); /* πŸ‘ˆ */

server.listen(3000);

6. Profit πŸ€‘

// client.ts
const res = await fetch('http://localhost:3000/say-hello?name=James', { method: 'GET' });
const body = await res.json(); /* { greeting: 'Hello James!' } */

Requirements

Peer dependencies:

  • tRPC Server v10 (@trpc/server) must be installed.
  • Zod v3 (zod@^3.14.4) must be installed (recommended ^3.20.0).

For a procedure to support OpenAPI the following must be true:

  • Both input and output parsers are present AND use Zod validation.
  • Query input parsers extend Object<{ [string]: String | Number | BigInt | Date }> or Void.
  • Mutation input parsers extend Object<{ [string]: AnyType }> or Void.
  • meta.openapi.method is GET, POST, PATCH, PUT or DELETE.
  • meta.openapi.path is a string starting with /.
  • meta.openapi.path parameters exist in input parser as String | Number | BigInt | Date

Please note:

  • Data transformers (such as superjson) are ignored.
  • Trailing slashes are ignored.
  • Routing is case-insensitive.

HTTP Requests

Procedures with a GET/DELETE method will accept inputs via URL query parameters. Procedures with a POST/PATCH/PUT method will accept inputs via the request body with a application/json or application/x-www-form-urlencoded content type.

Path parameters

A procedure can accept a set of inputs via URL path parameters. You can add a path parameter to any OpenAPI procedure by using curly brackets around an input name as a path segment in the meta.openapi.path field.

Query parameters

Query & path parameter inputs are always accepted as a string. This library will attempt to coerce your input values to the following primitive types out of the box: number, boolean, bigint and date. If you wish to support others such as object, array etc. please use z.preprocess().

// Router
export const appRouter = t.router({
  sayHello: t.procedure
    .meta({ openapi: { method: 'GET', path: '/say-hello/{name}' /* πŸ‘ˆ */ } })
    .input(z.object({ name: z.string() /* πŸ‘ˆ */, greeting: z.string() }))
    .output(z.object({ greeting: z.string() }))
    .query(({ input }) => {
      return { greeting: `${input.greeting} ${input.name}!` };
    });
});

// Client
const res = await fetch('http://localhost:3000/say-hello/James?greeting=Hello' /* πŸ‘ˆ */, {
  method: 'GET',
});
const body = await res.json(); /* { greeting: 'Hello James!' } */

Request body

// Router
export const appRouter = t.router({
  sayHello: t.procedure
    .meta({ openapi: { method: 'POST', path: '/say-hello/{name}' /* πŸ‘ˆ */ } })
    .input(z.object({ name: z.string() /* πŸ‘ˆ */, greeting: z.string() }))
    .output(z.object({ greeting: z.string() }))
    .mutation(({ input }) => {
      return { greeting: `${input.greeting} ${input.name}!` };
    });
});

// Client
const res = await fetch('http://localhost:3000/say-hello/James' /* πŸ‘ˆ */, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ greeting: 'Hello' }),
});
const body = await res.json(); /* { greeting: 'Hello James!' } */

Custom headers

Any custom headers can be specified in the meta.openapi.headers array, these headers will not be validated on request. Please consider using Authorization for first-class OpenAPI auth/security support.

HTTP Responses

Status codes will be 200 by default for any successful requests. In the case of an error, the status code will be derived from the thrown TRPCError or fallback to 500.

You can modify the status code or headers for any response using the responseMeta function.

Please see error status codes here.

Authorization

To create protected endpoints, add protect: true to the meta.openapi object of each tRPC procedure. You can then authenticate each request with the createContext function using the Authorization header with the Bearer scheme.

Explore a complete example here.

Server

import { TRPCError, initTRPC } from '@trpc/server';
import { OpenApiMeta } from 'trpc-openapi';

type User = { id: string; name: string };

const users: User[] = [
  {
    id: 'usr_123',
    name: 'James',
  },
];

export type Context = { user: User | null };

export const createContext = async ({ req, res }): Promise<Context> => {
  let user: User | null = null;
  if (req.headers.authorization) {
    const userId = req.headers.authorization.split(' ')[1];
    user = users.find((_user) => _user.id === userId);
  }
  return { user };
};

const t = initTRPC.context<Context>().meta<OpenApiMeta>().create();

export const appRouter = t.router({
  sayHello: t.procedure
    .meta({ openapi: { method: 'GET', path: '/say-hello', protect: true /* πŸ‘ˆ */ } })
    .input(z.void()) // no input expected
    .output(z.object({ greeting: z.string() }))
    .query(({ input, ctx }) => {
      if (!ctx.user) {
        throw new TRPCError({ message: 'User not found', code: 'UNAUTHORIZED' });
      }
      return { greeting: `Hello ${ctx.user.name}!` };
    }),
});

Client

const res = await fetch('http://localhost:3000/say-hello', {
  method: 'GET',
  headers: { Authorization: 'Bearer usr_123' } /* πŸ‘ˆ */,
});
const body = await res.json(); /* { greeting: 'Hello James!' } */

Examples

For advanced use-cases, please find examples in our complete test suite.

With Express

Please see full example here.

import { createExpressMiddleware } from '@trpc/server/adapters/express';
import express from 'express';
import { createOpenApiExpressMiddleware } from 'trpc-openapi';

import { appRouter } from '../appRouter';

const app = express();

app.use('/api/trpc', createExpressMiddleware({ router: appRouter }));
app.use('/api', createOpenApiExpressMiddleware({ router: appRouter })); /* πŸ‘ˆ */

app.listen(3000);

With Next.js

Please see full example here.

// pages/api/[...trpc].ts
import { createOpenApiNextHandler } from 'trpc-openapi';

import { appRouter } from '../../server/appRouter';

export default createOpenApiNextHandler({ router: appRouter });

With AWS Lambda

Please see full example here.

import { createOpenApiAwsLambdaHandler } from 'trpc-openapi';

import { appRouter } from './appRouter';

export const openApi = createOpenApiAwsLambdaHandler({ router: appRouter });

Types

GenerateOpenApiDocumentOptions

Please see full typings here.

PropertyTypeDescriptionRequired
titlestringThe title of the API.true
descriptionstringA short description of the API.false
versionstringThe version of the OpenAPI document.true
baseUrlstringThe base URL of the target server.true
docsUrlstringA URL to any external documentation.false
tagsstring[]A list for ordering endpoint groups.false

OpenApiMeta

Please see full typings here.

PropertyTypeDescriptionRequiredDefault
enabledbooleanExposes this procedure to trpc-openapi adapters and on the OpenAPI document.falsetrue
methodHttpMethodHTTP method this endpoint is exposed on. Value can be GET, POST, PATCH, PUT or DELETE.trueundefined
pathstringPathname this endpoint is exposed on. Value must start with /, specify path parameters using {}.trueundefined
protectbooleanRequires this endpoint to use an Authorization header credential with Bearer scheme on OpenAPI document.falsefalse
summarystringA short summary of the endpoint included in the OpenAPI document.falseundefined
descriptionstringA verbose description of the endpoint included in the OpenAPI document.falseundefined
tagsstring[]A list of tags used for logical grouping of endpoints in the OpenAPI document.falseundefined
headersParameterObject[]An array of custom headers to add for this endpoint in the OpenAPI document.falseundefined
contentTypesContentType[]A set of content types specified as accepted in the OpenAPI document.false['application/json']

CreateOpenApiNodeHttpHandlerOptions

Please see full typings here.

PropertyTypeDescriptionRequired
routerRouterYour application tRPC router.true
createContextFunctionPasses contextual (ctx) data to procedure resolvers.false
responseMetaFunctionReturns any modifications to statusCode & headers.false
onErrorFunctionCalled if error occurs inside handler.false
maxBodySizenumberMaximum request body size in bytes (default: 100kb).false

Still using tRPC v9? See our .interop() example.


Download Details:

Author: jlalmes
Source Code: https://github.com/jlalmes/trpc-openapi 
License: MIT license

#typescript #nodejs #rest #swagger #openapi #trpc