Build API clients for Java

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

Required tools

Create a project

Use Gradle to initialize a Java application project.

gradle init --dsl groovy --test-framework junit --type java-application --project-name kiotaposts --package kiotaposts

Project configuration

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

  • build.gradle > compileJava > sourceCompatibility set to "1.8" or later. (or equivalent if you're not using gradle)
  • build.gradle > compileJava > targetCompatibility set to "1.8" or later. (or equivalent if you're not using gradle)
  • Java Development Kit (JDK) version 17 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.

Edit ./app/build.gradle to add the following dependencies.

Note

Find current version numbers for Kiota packages at Nexus Repository Manager.

implementation 'jakarta.annotation:jakarta.annotation-api:3.0.0'
implementation 'com.microsoft.kiota:microsoft-kiota-bundle:1.7.0'

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 java -c PostsClient -n kiotaposts.client -d ./posts-api.yml -o ./app/src/main/java/kiotaposts/client --ds none -s none

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

The final step is to update the ./app/src/main/java/kiotaposts/App.java file that was generated as part of the console application, replacing its contents with the following code.

package kiotaposts;

import java.util.List;

import com.microsoft.kiota.authentication.AnonymousAuthenticationProvider;
import com.microsoft.kiota.bundle.DefaultRequestAdapter;

import kiotaposts.client.PostsClient;
import kiotaposts.client.models.Post;

public class App {

    public static void main(String[] args) {
        // API requires no authentication, so use the anonymous
        // authentication provider
        final AnonymousAuthenticationProvider authProvider =
            new AnonymousAuthenticationProvider();
        final DefaultRequestAdapter adapter = new DefaultRequestAdapter(authProvider);

        final PostsClient client = new PostsClient(adapter);

        // GET /posts
        final List<Post> allPosts = client.posts().get();
        System.out.printf("Retrieved %d posts.%n", allPosts.size());

        // GET /posts/{id}
        final Integer specificPostId = 5;
        final Post specificPost = client.posts().byPostId(specificPostId).get();
        System.out.printf("Retrieved post - ID: %d, Title: %s, Body: %s%n",
            specificPost.getId(), specificPost.getTitle(), specificPost.getBody());

        // POST /posts
        final Post newPost = new Post();
        newPost.setUserId(42);
        newPost.setTitle("Testing Kiota-generated API client");
        newPost.setBody("Hello world!");

        final Post createdPost = client.posts().post(newPost);
        System.out.printf("Created new post with ID: %d%n", createdPost.getId());

        // PATCH /posts/{id}
        final Post update = new Post();
        // Only update title
        update.setTitle("Updated title");

        final Post updatedPost = client.posts().byPostId(specificPostId).patch(update);
        System.out.printf("Updated post - ID: %d, Title: %s, Body: %s%n",
            updatedPost.getId(), updatedPost.getTitle(), updatedPost.getBody());

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

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.

./gradlew --console plain run

See also

(UNOFFICIAL) Community tools and libraries

Important

The Kiota Community tools and libraries are maintained and distributed by the community and are not official Microsoft tools and libraries. Microsoft makes no warranties, express or implied, with respect to the tools and libraries or their use. Use of the tools and libraries at your own risk. Microsoft shall not be liable for any damages arising out of or in connection with the use of the tools and libraries.

There are community tools and libraries to make it easy for you to get started with Kiota and to better harmonize the class path according to the rest of your stack: