Επεξεργασία

Κοινή χρήση μέσω


Build API clients for Dart

In this tutorial, you build a sample app in Dart that calls a REST API that doesn't require authentication.

Required tools

Create a project

Run the following commands in the directory where you want to create a new project.

dart create -t console cli

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the bundle package. For more information about Kiota dependencies, see the dependencies documentation.

Run the following commands to get the required dependencies.

dart pub add microsoft_kiota_bundle

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named posts-api.yml and add the following.

openapi: '3.0.2'
info:
  title: JSONPlaceholder
  version: '1.0'
servers:
  - url: https://jsonplaceholder.typicode.com/

components:
  schemas:
    post:
      type: object
      properties:
        userId:
          type: integer
        id:
          type: integer
        title:
          type: string
        body:
          type: string
  parameters:
    post-id:
      name: post-id
      in: path
      description: 'key: id of post'
      required: true
      style: simple
      schema:
        type: integer

paths:
  /posts:
    get:
      description: Get posts
      parameters:
      - name: userId
        in: query
        description: Filter results by user ID
        required: false
        style: form
        schema:
          type: integer
          maxItems: 1
      - name: title
        in: query
        description: Filter results by title
        required: false
        style: form
        schema:
          type: string
          maxItems: 1
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/post'
    post:
      description: 'Create post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/post'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
  /posts/{post-id}:
    get:
      description: 'Get post by ID'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
    patch:
      description: 'Update post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/post'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
    delete:
      description: 'Delete post'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK

This file is a minimal OpenAPI description that describes how to call the /posts endpoint in the JSONPlaceholder REST API.

You can then use the Kiota command line tool to generate the API client classes.

kiota generate -l dart -d posts-api.yml -c PostsClient -o ./client

Tip

Add --exclude-backward-compatible if you want to reduce the size of the generated client and are not concerned about potentially source breaking changes with future versions of Kiota when updating the client.

Create the client application

Create a file in the root of the project named index.ts and add the following code.

import '../client/posts_client.dart';
import '../client/models/post.dart';
import 'package:microsoft_kiota_bundle/microsoft_kiota_bundle.dart';
import 'package:microsoft_kiota_abstractions/microsoft_kiota_abstractions.dart';

void main(List<String> arguments) async {
  var authenticationProvider = AnonymousAuthenticationProvider();
  var requestAdapter =
      DefaultRequestAdapter(authProvider: authenticationProvider);
  var client = PostsClient(requestAdapter);

  // GET /posts
  var posts = await client.posts.getAsync();
  print('Posts: ${posts?.length ?? 0}');

  // GET /posts/{id}
  var specificPostId = 5;
  var specificPost = await client.posts.byPostId(specificPostId).getAsync();
  print(
      'Retrieved post - ID: ${specificPost?.id}, Title: ${specificPost?.title}, Body: ${specificPost?.body}');

  // POST /posts
  var newPost = Post();
  newPost.body = 'Hello world';
  newPost.title = 'Testing Kiota-generated API client';
  newPost.userId = 42;
  var createdPost = await client.posts.postAsync(newPost);
  print('Created new post with ID: ${createdPost?.id}');

  // PATCH /posts/{id}
  var updatePost = Post();
  updatePost.title = 'Updated title';
  var updatedPost =
      await client.posts.byPostId(specificPostId).patchAsync(updatePost);
  print(
      'Updated post - ID: ${updatedPost?.id}, Title: ${updatedPost?.title}, Body: ${updatedPost?.body}');

  // DELETE /posts/{id}
  await client.posts.byPostId(specificPostId).deleteAsync();
}

Note

The JSONPlaceholder REST API doesn't require any authentication, so this sample uses the AnonymousAuthenticationProvider. For APIs that require authentication, use an applicable authentication provider.

Run the application

To start the application, run the following command in your project directory.

dart run

See also