Building an API with Scratch

Do you feel the need to teach kids to program but want to suck the fun out of it? This is your article.
By Ricardo Devis Posted 06 October 2016

Building an API with Scratch

We are starting an initiative here in Bilbao to get kids to learn programming, and while I think it's a wonderful idea, kids should be prepared for the harsh truth. Programming is not fun. Programming shouldn't be fun. Programming is serious business for serious people. Let's forget those silly animated cats, and let's teach kids what is like to program a REST API. After all, this is not about them! It's about us!

The game

The Game

So the game is pretty simple. You have your server and your client, represented by the Chrome icon, because, well, kids should know who's king. You'll notice that I also have two global variables to pass messages from one object to another. I know, it's horrible, and you should tell your kids every five minutes that they are bad. But if they ask why you are using it then, just tell them that you know better, and don't dare to question your authority!

We'll start with the simpler part one first, the database server (as it should be! some of us would say).

The server

The Game Server

On the top we have our four classic CRUD operations, followed by two private functions. Since Scratch is silly and by default broadcasts messages to everyone (unless you do this little hack), we namespace them. One function to validate that the index requested exists, and another to send data.

You'll see that on the SendData function there's a random check that sends an error message one out of five times. That will teach the kids that life isn't fair, and sometimes things crash just because they do.

The client

The Game Client

At this stage kids will probably be in awe about the important programming concepts that we deal every day, but they are still for a treat with this one.

So on the right we got our forever-loop-main function that just deals with the different possible operations (again, all with broadcast functions (refactor, son!)) and an error case. On the left, some helper functions to put messages on the screen.

The Game

I just put one example with the PUT method, but the rest follow the same logic. Basically, we ask the data and send it. Since we do the same for every method, let's refactor again, and also, we validate the number input. Scratch is weird with the data input, so we just add one and check the sum. Since index zero doesn't exist on the list (I know, you are furious about this), this should work.

And this is it, folks. If your kid still has brain cells after this point, you know he will be one of us.

If you want to contribute to this wonderful project, here's the link (I accept PR).

Ricardo Devis
Ricardo Devis
Software Engineer