At my job I use Mulesoft to put together APIs for accessing data. It gives you a graphical interface to easily design your flow, and the connectors they provide make it easy to connect to different resources. I’m learning the Go programming language, so I wanted to try to put together a simple API in code.
I put together a simple console app earlier, to look up players on a team’s roster.
Building on that, I created a CRUD API to add and remove records, as well as look them up. The API interacts with a Postgres database.
Here’s the source code on GitHub
Here’s a SQL script on GitHub to create a roster table with a few player records.
The app uses several code files. The main file is the entry point, plus it stores any utility functions.
The handler file has a method for each API call available. It also takes care of formatting the output.
The database file handles any interaction with the database. Plus there are separate files for validation of input, as well as handling configuration for the service.
I do use a third party package (gorilla/mux) for routing. Go includes some routing capability natively, but Gorilla also lets you specify HTTP methods to handle.
I did run into two issues that held me up for a bit. When creating my Player struct, I used a lower case letter for the start of each property. It turns out that Go requires you to capitalize the property name, if you want the property to be Global. Since I had my struct in the Main file, I couldn’t reference the properties from the Database file until the attribute names were updated to start with a capital letter.
Also, when building the output to return from the API, data wasn’t recognized as Json, just as text. When writing to the ResponseWriter, the first thing you do needs to be to set the Content Type to application/json. I was doing that, but not as the first call.
There’s a few other things I probably need to do with the API. As I did with the console app, I just have the database credentials stored in the code. Not a huge deal with a demo app, but a real app wouldn’t do that. I also need to add more data validation for any inputs, and I would probably need some logging for a real app, to track an errors or warnings. Also, to be production ready, I would need to think about versioning, authentication, and possibly throttling of attempts. But this was a great exercise to learn the basics of Go.