Building Microservices with Python, Part 3

Building the first endpoint

Updating the OpenAPI Spec

In this first endpoint, we are going to index rooms to Elasticsearch. For that reason, we need to update the OpenApi Spec to include this new endpoint with the proper configuration.

Remember that you can find all the code in this repository.

Setting up your configuration

In the previous article, we defined a docker-compose with a couple of dependencies. At this time, we need to have in some place the configuration to connect to Elasticsearch.

export ELASTICSEARCH_HOST=127.0.0.1
export ELASTICSEARCH_PORT=9200

Setting up Elasticsearch

Before to jump to the task to build the endpoint, we need to have a way to connect to Elasticsearch and be able to inject it to our controller.

  • Make the connection to Elasticsearch, it will connect just once and check if the index should be created.
  • Index a new room given the payload
  • Check if a certain room already exists given an URL
  • geo_point, this is useful when we need to index coordinates. A geo_point structure stores a latitude and longitude.
  • keyword, this is used when we need to do the match against a specific value, for instance, a category name, or in this example an URL.

Binding the Elasticsearch in the container

Finally, we have our Elasticsearch dependencies set up, we can start working on inject the ElasticSearchIndex class in our post method.

Building the post action

We are getting closer; this is the last step. We need to create the post action that will receive the Room payload in the body, and it will index it on Elasticsearch.

  • We are injecting the ElasticSearchIndex service to this method.
  • We are validating that the room URL does not exist in the index already. If it is exist we return a 409 (Conflict) status code
  • If the room has been successfully indexed we return 201 status code
  • If the room it is not indexed we return a 400 (Bad Request) status code

Conclusion

In this article, we learned how to create a complex OpenApi Spec configuration with several nested definitions on it. We introduce some basic concepts of Elasticsearch and finally included a more complex dependency in our container.

Recommended book

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sergio Sola

Sergio Sola

Director of Engineering at Timescale