Create and list Kafka topics in Java

We have seen how to create, list and manage topics using Kafka console. Kafka console is good for practice and testing your code. But in production, we will need to use some API to interact with Apache Kafka. So, we will explore how to use Java and Python API with Apache Kafka. In this article, We will learn to Create and list Kafka topics in Java.

Create Kafka topics in Java

We can use ‘kafka.zk.AdminZkClient’ library to create topics and change their configuration using Java code.

First, we need to connect to the Zookeeper server and establish ZkUtils session.

Once our session is established, we can start creating our topic. We can pass the topic configuration while creating a new topic.

Once the topic configuration is fixed, we can create the topic using the following command.

After running this code, a topic named ‘myTopic’ will be created with three partitions and one replication factor.

Listing topic configuration

We can get topic configuration using the following method.

Checking topic existence

We need to check if some topic is already present in Kafka server before creating it. We can use the following function to check that

Changing topic configuration

We can modify topic configuration using the following function

Listing topics

We need to create Kafka consumer to list all topics in the Kafka server. Then we can use its ‘listTopic’ method to list all topics.

This will return all the topics in Kafka server.

Deleting Kafka topic

Though it is not often we need to delete Kafka topics; We can use the following method to do so.

I hope you have learned how we can manage topics in the Kafka server using Java. You can find this detailed code at git repository.

In the next article, we will see how to write Kafka Producer using Java. Till then, Happy learning.

Similar Posts

Leave a Reply

Your email address will not be published.


  1. If the zookeepers are locked. this code is throwing the below error
    Exception in thread “main” kafka.admin.AdminOperationException: org.apache.zookeeper.KeeperException$InvalidACLException: KeeperErrorCode = InvalidACL for /brokers/topics/myTopic1
    at kafka.zk.AdminZkClient.writeTopicPartitionAssignment(AdminZkClient.scala:162)
    at kafka.zk.AdminZkClient.createOrUpdateTopicPartitionAssignmentPathInZK(AdminZkClient.scala:102)
    at kafka.zk.AdminZkClient.createTopic(AdminZkClient.scala:56)
    Any methods available to unlock/lock the zookeeper?

  2. Hi Mahesh,

    Have you tried API for creating topics for the brokers configured with SASL_SSL authentication if ,so can you please share the code.