If you try to create topic that is already exist then Kafka admin client raise Exception TopicAlreadyExistsError so you can handle that exception in your code like I did...
Let me provide you the sample code I built for my use case
def create_topic(self, topic_name=None, num_partitions=1, replication_factor=1):
try:
topic_list = []
topic_list.append(NewTopic(name=topic_name, num_partitions=num_partitions, replication_factor=replication_factor))
self.admin_client.create_topics(new_topics=topic_list, validate_only=False)
self.show_topic_on_console()
return True
except TopicAlreadyExistsError as err:
print(f"Request for topic creation is failed as {topic_name} is already created due to {err}")
return False
except Exception as err:
print(f"Request for topic creation is failing due to {err}")
return False
Alternative flow - you can design like below
- Extract list of the topics
- Check whether request topic in the list
or not
- If not in the list the create topic