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
- Create a new Flutter 3.10 (or later)
Application
project in Visual Studio Code: steps - Add the openapi_generator package to your project. Follow below steps instead of the instructions at pub.dev (at the time of writing they were out of date):
- Include
openapi_generator_annotations
in thedependencies
section of yourpubspec.yaml
file :dependencies: openapi_generator_annotations: ^4.10.0
- Include
build_runner
andopenapi_generator
in thedev_dependencies
section of yourpubspec.yaml
file:dev_dependencies: build_runner: openapi_generator: ^4.10.0
- Annotate a dart class with the
@Openapi()
annotation; specify the path to your OpenApi json file in theinputSpecFile
parameter (note that paths are relative to the project root folder):import 'package:openapi_generator_annotations/openapi_generator_annotations.dart'; @Openapi( additionalProperties: 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
- Include
- To use the generated client in your project, follow the instructions in the generated
README.md
(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.:
dependencies: example_api: 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(); print(result); } catch (e) { print('Exception when calling AspNet8CoreAPIVersion1000CultureneutralPublicKeyTokennullApi->todosGet: $e\n'); }
- how to add the generated package from your local disk as a dependency in your project, e.g.: