Build API clients for Go

In this tutorial, you will build a sample app in Go that calls a REST API that does not 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 will 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 of the following packages.

For this tutorial, you will use the default implementations.

Run the following commands to get the required dependencies.

go get github.com/microsoft/kiota-abstractions-go
go get github.com/microsoft/kiota-http-go
go get github.com/microsoft/kiota-serialization-form-go
go get github.com/microsoft/kiota-serialization-json-go
go get github.com/microsoft/kiota-serialization-text-go
go get github.com/microsoft/kiota-serialization-multipart-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 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

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"
    http "github.com/microsoft/kiota-http-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 := http.NewNetHttpRequestAdapter(&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

Run the following command in your project directory to start the application.

go run .

See also