Skip to content

Instantly share code, notes, and snippets.

Last active May 25, 2023 10:54
Show Gist options
  • Save VincentH-Net/9451ed2f993f84eff053a854944df99c to your computer and use it in GitHub Desktop.
Save VincentH-Net/9451ed2f993f84eff053a854944df99c to your computer and use it in GitHub Desktop.
Use OpenApi in Flutter

To generate an API client in Dart from an OpenApi.json file, and use it in Flutter, follow these steps:

Related: see this gist for how to generate an OpenApi.json file on build from an ASP.NET 8 Minimal API project

  1. Create a new Flutter 3.10 (or later) Application project in Visual Studio Code: steps
  2. Add the openapi_generator package to your project. Follow below steps instead of the instructions at (at the time of writing they were out of date):
    • Include openapi_generator_annotationsin the dependencies section of your pubspec.yaml file :
        openapi_generator_annotations: ^4.10.0
    • Include build_runner and openapi_generator in the dev_dependencies section of your pubspec.yaml file:
         openapi_generator: ^4.10.0
    • Annotate a dart class with the @Openapi() annotation; specify the path to your OpenApi json file in the inputSpecFile parameter (note that paths are relative to the project root folder):
      import 'package:openapi_generator_annotations/openapi_generator_annotations.dart';
          AdditionalProperties(pubName: 'example_api', pubAuthor: 'Your_Name'),
          inputSpecFile: '../Api/bin/Debug/net8.0/openapi.json',
          generatorName: Generator.dart,
          outputDirectory: 'apiclient')
      class Example extends OpenapiGeneratorConfig {}
    • Run this command to generate the OpenApi client from the json file that you specified in the annotation:
      dart run build_runner build --delete-conflicting-outputs
  3. To use the generated client in your project, follow the instructions in the generated (in the folder you specified in the @Openapi() outputDirectory parameter).
    Note that the instructions include:
    • how to add the generated package from your local disk as a dependency in your project, e.g.:
          path: apiclient
    • a dart code snippet that shows the generated class name and a method call specifically for your API. You can use the class and method names from the README, but you need to add a base URL and a missing await, e.g. like this:
      import 'package:example_api/api.dart';
      final api_instance = AspNet8CoreAPIVersion1000CultureneutralPublicKeyTokennullApi(ApiClient(basePath: 'http://localhost:5139'));
      try {
          final result = await api_instance.todosGet();
      } catch (e) {
          print('Exception when calling AspNet8CoreAPIVersion1000CultureneutralPublicKeyTokennullApi->todosGet: $e\n');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment