Muokkaa

Jaa


Build API clients for Go

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

Required tools

Create a project

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

go mod init kiota_posts

Project configuration

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

  • go.mod > go set to version 18 or above.

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.

go get github.com/microsoft/kiota-bundle-go

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 go -c PostsClient -n kiota_posts/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.go and add the following code.

package main

import (
    "context"
    "fmt"
    "log"

    "kiota_posts/client"
    "kiota_posts/client/models"

    auth "github.com/microsoft/kiota-abstractions-go/authentication"
    bundle "github.com/microsoft/kiota-bundle-go"
)

func main() {
    // API requires no authentication, so use the anonymous
    // authentication provider
    authProvider := auth.AnonymousAuthenticationProvider{}

    // Create request adapter using the net/http-based implementation
    adapter, err := bundle.NewDefaultRequestAdapter(&authProvider)
    if err != nil {
        log.Fatalf("Error creating request adapter: %v\n", err)
    }

    // Create the API client
    client := client.NewPostsClient(adapter)

    // GET /posts
    allPosts, err := client.Posts().Get(context.Background(), nil)
    if err != nil {
        log.Fatalf("Error getting posts: %v\n", err)
    }
    fmt.Printf("Retrieved %d posts.\n", len(allPosts))

    // GET /posts/{id}
    specificPostId := int32(5)
    specificPost, err := client.Posts().ByPostIdInteger(specificPostId).Get(context.Background(), nil)
    if err != nil {
        log.Fatalf("Error getting post by ID: %v\n", err)
    }
    fmt.Printf("Retrieved post - ID: %d, Title: %s, Body: %s\n", *specificPost.GetId(), *specificPost.GetTitle(), *specificPost.GetBody())

    // POST /posts
    newPost := models.NewPost()
    userId := int32(42)
    newPost.SetUserId(&userId)
    title := "Testing Kiota-generated API client"
    newPost.SetTitle(&title)
    body := "Hello world!"
    newPost.SetBody(&body)

    createdPost, err := client.Posts().Post(context.Background(), newPost, nil)
    if err != nil {
        log.Fatalf("Error creating post: %v\n", err)
    }
    fmt.Printf("Created new post with ID: %d\n", *createdPost.GetId())

    // PATCH /posts/{id}
    update := models.NewPost()
    newTitle := "Updated title"
    update.SetTitle(&newTitle)

    updatedPost, err := client.Posts().ByPostIdInteger(specificPostId).Patch(context.Background(), update, nil)
    if err != nil {
        log.Fatalf("Error updating post: %v\n", err)
    }
    fmt.Printf("Updated post - ID: %d, Title: %s, Body: %s\n", *updatedPost.GetId(), *updatedPost.GetTitle(), *updatedPost.GetBody())

    // DELETE /posts/{id}
    _, err = client.Posts().ByPostIdInteger(specificPostId).Delete(context.Background(), nil)
    if err != nil {
        log.Fatalf("Error deleting post: %v\n", err)
    }
    fmt.Printf("Deleted post\n")
}

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.

go run .

See also