Giter Site home page Giter Site logo

open_api's Introduction

Shelf Open Api

The purpose of this library is to expose the generation of file with open api specifications from your shelf controllers OpenApi Specification

This library is under development, any help is welcome

Features

  • Info (Versioning, EndPoint and more api info)
  • Params (Supported only string type params)
  • Requests
  • Responses
  • Bad Responses
  • Reused schemas by $ref
  • Inheritance and Polymorphism by allOf, oneOf, anyOf, discriminator
  • json_serializable annotations
  • [-] Security (Partial implemented)
  • Docs (summary, description, example)
  • Tags/Groups
  • Deprecated operations by @Deprecated() meta annotation
  • Default values default

Install package

To use shelf_open_api, you will need your typical build_runner/code-generator setup. First, install build_runner, shelf_open_api, shelf_open_api_generator by adding them to your pubspec.yaml file:

# pubspec.yaml
dependencies:
  shelf_open_api:

dev_dependencies:
  build_runner:
  shelf_open_api_generator:

Usage

You can see some examples in example folder.

Run the code generator, you can use:

  • <dart|flutter> pub run build_runner build

You can see the generated result in the public folder!

Done! See options for more info/configurations. But now let's type the routes!

Use OpenApiRoute on routes where the query type or body type needs to be defined. Remember that you can define the summary and description for each route. The summary is the first line of each method and must only be in one line otherwise it will be a description of your route. The JsonResponse class can be found in the example. Should I add it to shelf_open_api package?

class MessagesController {
  @Route.get('/messages')
  @OpenApiRoute(requestQuery: MessageFetchDto)
  Future<JsonResponse<void>> fetch(Request request) async {
    // Code...
  }
  
  /// This is a summary
  /// 
  /// This is a
  /// long description
  @Route.post('/messages')
  @OpenApiRoute(requestBody: MessageCreateDto)
  Future<JsonResponse<void>> create(Request request) async {
    // Code...
  }
}

You can define summaries, descriptions and examples for your queries or requests as well

class MessageCreateDto {
  /// The id of the chat where the message will be sent
  final String chatId;
  /// The content of the message.
  /// 
  /// You can enter texts and emojis. Images are not supported.
  /// 
  /// `Hi, Luigi!`
  final String content;

  const MessageCreateDto({
    required this.chatId,
    required this.content,
  });
}

Options

You can find many other configuration parameters by looking at the config file.

targets:
  $default:
    builders:
      shelf_open_api_generator:
        options:
          include_routes_in: 'lib/**_controller.dart'
          info_title: 'Api'
          security_schemes:
             appwriteJwt:
               type: http
               scheme: Bearer
               bearerFormat: JWT

Shelf Routing

Have too many controllers in your app? This could save you!

Write something down with Routing and a file with all the controllers in your app will be generated!

@Routing(
  varName: 'controllersRouter',
  generateFor: ['**/*_controller.dart'],
)
void main() {
  // ...
}

// *.g.dart

import 'package:shelf_router/shelf_router.dart';
import 'package:app/features/chats/controllers/chats_controller.dart';
import 'package:app/features/messages/controllers/messages_controller.dart';
import 'package:app/features/users/controllers/users_controller.dart';

final $controllersRouter = Router()
  ..mount('/v1', UsersController().router)
  ..mount('/v1', MessagessController().router)
  ..mount('/v1', ChatsController().router);

This allows you to annotate your controllers with @Routes(prefix: '/v1') to prefix all controller routes. This annotation is not mandatory!

@Routes(prefix: '/v1')
class MessagesController {
  // ...
}

Options

targets:
  $default:
    builders:
      shelf_open_api_generator:shelf_routing:
        generate_for:
          - '**/*_api.dart'

More

open_api_client_generator The purpose of this library is to expose the generation of file with open api specifications from your shelf controllers

open_api's People

Contributors

brex900 avatar

Stargazers

GiKode avatar  avatar Bartosz Pijet avatar José Morais avatar

Watchers

 avatar  avatar

open_api's Issues

Generating the open_api.yaml

Hi I am trying to generate the OpenApi.yaml file but seems like the build runner is not generating it. It generates the controllers fine however the yaml does not get generated.

import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_open_api/shelf_routing.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_static/shelf_static.dart';
import 'package:shelf_swagger_ui/shelf_swagger_ui.dart';

import 'listener_package.routing.dart';

@Routing(
  varName: 'controllersRouter',
  generateFor: ['**/*_controller.dart'],
)
class Server {
  final int port;
  final InternetAddress ip;
  final bool permissions;
  late final Router router;

  Server ({
    int? port,
    InternetAddress? ip,
    bool? permissions,
  })  : port = port ?? 6565,
        ip = ip ?? InternetAddress.anyIPv4,
        permissions = permissions ?? false;

  Future<void> startServer() async {
    final rootRouter = Router()
      ..mount('/', $controllersRouter)
      ..mount(
          '/swagger',
          SwaggerUI('public/example.open_api.yaml',
              title: 'Swagger Example Api'))
      ..mount('/', createStaticHandler('public'));

    // Configure a pipeline.
    final handler = Pipeline().addHandler(rootRouter);

    final server = await serve(handler, ip, port);

    final url = 'http://${server.address.address}:${server.port}';
    print('Server listening on $url -> Swagger: $url/swagger');
  }
}
library listener_package;

import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_open_api/shelf_routing.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_static/shelf_static.dart';
import 'package:shelf_swagger_ui/shelf_swagger_ui.dart';

import 'listener_package.routing.dart';

@Routing(
  varName: 'controllersRouter',
  generateFor: ['**/*_controller.dart'],
)
class Listener {
  final int port;
  final InternetAddress ip;
  final bool permissions;
  late final Router router;

  Listener({
    int? port,
    InternetAddress? ip,
    bool? permissions,
  })  : port = port ?? 6565,
        ip = ip ?? InternetAddress.anyIPv4,
        permissions = permissions ?? false;

  Future<void> startServer() async {
    final rootRouter = Router()
      ..mount('/', $controllersRouter)
      ..mount(
          '/swagger',
          SwaggerUI('public/example.open_api.yaml',
              title: 'Swagger Example Api'))
      ..mount('/', createStaticHandler('public'));

    // Configure a pipeline.
    final handler = Pipeline().addHandler(rootRouter);

    final server = await serve(handler, ip, port);

    final url = 'http://${server.address.address}:${server.port}';
    print('Server listening on $url -> Swagger: $url/swagger');
  }
}

import 'package:scotch_pay_api/scotch_pay_api.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_open_api/shelf_open_api.dart';
import 'package:shelf_open_api/shelf_routing.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:listener_package/shared/json_response.dart';

part 'api_controller.g.dart';

@Routes()
class ApiController {
  const ApiController();

  Router get router => _$ApiControllerRouter(this);

  @Route.get('/endpoint')
  @OpenApiRoute(requestQuery: CustomDTO)
  Future<JsonResponse<List<CustomDTO>>> fetchMessages(
      Request request) async {
    // ...

    return JsonResponse.ok();
  }
}

The server operates fine its just the generation of the yaml that gives me an issue. @BreX900

When the generator starts, no documentation is generated

Even if I try to follow the guide from the repository using the example in it, nothing works. If I delete the example.openapi.yaml file, the system does not generate it again :(
Dart SDK version: 3.1.0 (stable) on "windows_x64"

I tried downgrading dart version but it didn't help:

fvm dart --version
Dart SDK version: 2.19.6 (stable) on "windows_x64"

Build_Runner runs into stackOverflow error when generating documentation

Hi @BreX900, I get this error when running the build_runner:

[INFO] Generating build script completed, took 348ms
[INFO] Precompiling build script... completed, took 6.2s
[INFO] Building new asset graph completed, took 1.2s
[INFO] Checking for unexpected pre-existing outputs. completed, took 3ms
[WARNING] No actions completed for 15.6s, waiting on:
  - shelf_router_generator:shelf_router on test/listener_package_test.dart
  - shelf_router_generator:shelf_router on test/stubs/test_data.dart
  - shelf_router_generator:shelf_router on lib/listener_package.dart
  - shelf_router_generator:shelf_router on lib/controllers/api_controller.dart
  - shelf_router_generator:shelf_router on lib/services/scotch_pay_service.dart

[WARNING] shelf_open_api_generator on $package$:
I cant create dynamic component schema!
[WARNING] shelf_open_api_generator on $package$:
Already exist TranRecord component schema with different type!
{TranRecord} | TranRecord?
[SEVERE] shelf_open_api_generator on $package$:

Stack Overflow
[INFO] Running build completed, took 30.4s
[INFO] Caching finalized dependency graph completed, took 122ms
[SEVERE] Failed after 30.5s

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.