Skip to main content

Tech Art Bits: Making a basic Web API with Clacks

If you read my first tutorial on "getting started with Clacks", you might have thought to yourself, not entirely unfairly, that it is not very convenient to _need_ clacks to talk to a clacks server. This is entirely true, and precisely for this reason, in this tutorial, we will be diving into creating a simple HTTP server using standard REST API methods (GET, POST).

In this tutorial, we will need two libraries as prerequisite installs for the code snippets to work, Which can both be found on the github pages that are linked if you click on them below.

Of course, as always, you can download the sample content for this tutorial here:

Table of Contents

Step 1: Create a simple REST API server

As before, you can see that the standard clacks_web library offers most of what you need out of the box. In fact, it takes fewer lines of code to build a simple REST API with clacks_web than it does to create a simple server with standard clacks!

Step 2: Let's test!

As you can see from the snippet below, issuing a simple request to a clacks web server like this does not require clacks! This means a client application that wants to issue a request to this server does not need the clacks package installed to talk to it! 


In fact, requests need not even come from python - you'll notice that if you just open your web browser (once this server instance is running) and navigate to its address, the standard web browser will just support the response and display it as plain text:

Step 3: Add your own commands

Now we can build our own interface! Just like before, we use the clacks.ServerInterface base class for this, however, this time, we will also use the clacks_web.get and clacks_web.post decorators, and use them on our methods. This will let the clacks Web Server know that these methods are marked as needing to be accessible through the GET and POST verbs, respectively. Without these decorators, these methods are inaccessible through normal HTTP requests.

Lastly, we just need to attach our custom interface to our server, and restart it;

And now, we can access our methods through the standard requests module!

I hope you enjoyed reading this tutorial as much as I did writing it! As always, don't hesitate to leave a comment, and if you wish, you can always suggest changes to the clacks extension libraries, that is why they are in the public domain!

Comments