編集

次の方法で共有


Build API clients for Python

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

Required tools

Create a project

Create a directory to contain the new project.

Project configuration

In case you're adding a Kiota client to an existing project, the following configuration is required:

  • pyproject.toml > project > requires-python set to ">=3.8".

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 abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages:

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies:

pip install microsoft-kiota-abstractions
pip install microsoft-kiota-http
pip install microsoft-kiota-serialization-json
pip install microsoft-kiota-serialization-text
pip install microsoft-kiota-serialization-form
pip install microsoft-kiota-serialization-multipart

Tip

It is recommended to use a package manager/virtual environment to avoid installing packages system wide. Read more here.

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 python -c PostsClient -n client -d ./posts-api.yml -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 main.py and add the following code.

import asyncio
from kiota_abstractions.authentication.anonymous_authentication_provider import (
    AnonymousAuthenticationProvider)
from kiota_http.httpx_request_adapter import HttpxRequestAdapter
from client.posts_client import PostsClient
from client.models.post import Post

async def main():
    # You may need this if your're using asyncio on windows
    # See: https://stackoverflow.com/questions/63860576
    # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    # API requires no authentication, so use the anonymous
    # authentication provider
    auth_provider = AnonymousAuthenticationProvider()
    # Create request adapter using the HTTPX-based implementation
    request_adapter = HttpxRequestAdapter(auth_provider)
    # Create the API client
    client = PostsClient(request_adapter)

    # GET /posts
    all_posts = await client.posts.get()
    print(f"Retrieved {len(all_posts)} posts.")

    # GET /posts/{id}
    specific_post_id = "5"
    specific_post = await client.posts.by_post_id(specific_post_id).get()
    print(f"Retrieved post - ID: {specific_post.id}, " +
          f"Title: {specific_post.title}, " +
          f"Body: {specific_post.body}")

    # POST /posts
    new_post = Post()
    new_post.user_id = 42
    new_post.title = "Testing Kiota-generated API client"
    new_post.body = "Hello world!"

    created_post = await client.posts.post(new_post)
    print(f"Created new post with ID: {created_post.id}")

    # PATCH /posts/{id}
    update = Post()
    # Only update title
    update.title = "Updated title"

    updated_post = await client.posts.by_post_id(specific_post_id).patch(update)
    print(f"Updated post - ID: {updated_post.id}, " +
          f"Title: {updated_post.title}, " +
          f"Body: {updated_post.body}")

    # DELETE /posts/{id}
    await client.posts.by_post_id(specific_post_id).delete()

# Run main
asyncio.run(main())

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.

python3 main.py

See also