Build a Golang RESTful Stock API With the Echo Framework

Create a blazingly fast stocks API

Gary Frederick
Better Programming

--

Photo by Markus Spiske on Unsplash

This article describes how to build a Golang restful API with an Echo framework that returns stock data from Yahoo Finance

Echo Server

Echo Framework

Fast and unfancy HTTP server framework for Go (Golang). Up to 10x faster than the rest.

-Echo

Echo makes it quite simple to build web applications and Restful APIs. If you have a Python background you might find the framework similar to Flask. Echo does not come with batteries included, there’s no skeleton generator like Django, and no one structures your application but you!

Web Application Structure

First, you need to think about the folders and file structure for your project. I want to follow MVC architecture, so we should have models, views and controllers. For this Restful API example, we won’t need views or models.

I will follow the following structure for my folder:

— controllers
— server.go

server.go

This is the entry point of your application. You can rename it but this file should be the main package for your application.

In Go programming, packages are important. Go programs only can start at the main package (package main):

https://gist.github.com/BetterProgramming/f99ebbc60b163ab531634ad4a46e11c4.js

server.go should include the main function (func main) which is the entry point of the Go program. I imported two packages to server.go:

  • github.com/labstack/echo: echo package is to use echo framework
  • github.com/labstack/echo/middleware: sub-package from echo for middleware.

In the main function I initialized the echo object with the following:

e := echo.New()

The following code is using middleware in our application. I’m using three middlewares:

Recover middleware recovers from panics anywhere in the chain, prints stack trace, and handles the control to the centralized HTTPErrorHandler.

  • Logger is for the server log.
  • CORS gives web servers cross-domain access controls, which enables secure cross-domain data transfers.

I started the echo web server on port 8000. (You can choose any port you prefer that is open) I also wrap the start functionality in a logger to catch any fatal errors.

e.Logger.Fatal(e.Start(":8000"))

Now, the app is running on localhost:8000 and 0.0.0.0:8000. But you might not see anything because you don’t have a handler method to manage the request.

Let just create a handler method in server.go:

Now, if you go to localhost:8000, you will see the HTML page with “Hello, Word.”

After that, I’ll create one controller for the application. This controller is for scraping stock data from Yahoo Finance. Echo does not need you to create separate files for handlers. However, putting every handler method in one file is messy and won’t be maintainable in the long run. We want a centralized location for our functions and tests. This is a style guide adopted by most Go developers to produce clean and maintainable code, making programs more modular makes them easier for the next developer to read.

I start by creating a new package for the controllers called controllers. Let’s create the price.go rest controller file under controllers.

controllers
| price.go

You may see some extra code for stream recovery in this file. I don’t want to cover too much detail as to why I implement this but I found a helpful explanation from Aldo Giambelluca as to why it’s important:

Think about the io.ReadCloser as a tap: You can get the water, but once it’s out it’s out.

-Aldo Giambelluca

Price.go

Now we can use the price controller method in server.go as follows:

In the Echo framework, there’s a separate structure for each controller. You cannot create a method with the same name throughout the whole package.

Demo

I used Postman for the demo but you are welcome to use any tool to send over a HTTP Request with JSON data in the body.

We begin by running the server:

go run server.go

Starting the Echo Server

Then we create a request in Postman. In our code we created ticker:name as our key-value pair for the request body. Here are some example bodies:

## Amazon ticker{ 
"ticker" : "AMZN"
}
## Apple ticker{
"ticker" : "AAPL"
}

## Tesla ticker
{
"ticker" : "TSLA"
}
Yay!

Conclusion

We created a Rest API in Echo using MVC architecture!

We now understand why we organize our files in a certain structure — to increase readability and maintainability for other developers. We also understand how to create other endpoints on our server with more modular code.

To see the source code of the project you can visit my Github repo.

I hope this will help you to build fun projects!

--

--