Building RESTful APIs with Go
Follow a Bitcoin quote from a saved CoinMarketCap response through DynamoDB to a Go HTTP handler. The path explains what a successful lookup can tell you about the quote’s age.
For a software deployment course at SUNY Oswego, I built a service to answer a small question about CoinMarketCap’s top 100 cryptocurrencies. If someone asks for BTC, what name, rank, and dollar price should come back? Making the HTTP route was the shortest part of the job. The interesting decisions were how a quote got there in the first place and what the service could promise about it.
Two programs and one table
The project has two Go programs with different schedules. The collector requests CoinMarketCap’s latest listings, decodes the response, and writes a record for each coin to DynamoDB. The HTTP service accepts requests whenever a reader has a question. It reads the database, so ten people looking up Bitcoin do not trigger ten calls to CoinMarketCap. A reader can also retrieve the last stored price while the collector waits for its next poll. Collector loop.
The upstream response has a nested structure. Each entry carries a name and symbol, a field called cmc_rank, and a quote object containing values for USD. My DBitem type keeps four fields. The collector copies the rank, name, symbol, and price into that type, then sends it to DynamoDB with PutItem. Market capitalization appears in the upstream data, but it drops out at this step. Adding it to the HTTP response later would also require changing what the collector stores.
Following one Bitcoin quote
The repository includes a saved listing with 100 entries. Its Bitcoin record has rank 1 and a USD price of 61422.28861379695. That file gives me a fixed input for tracing a lookup without depending on today’s market. Given that record in the table, a request to GET /mcruz/search?coinName=BTC would produce this JSON, shown here with the whitespace expanded. Saved input record.
[
{
"coinRank": 1,
"coinName": "Bitcoin",
"coinSymbol": "BTC",
"coinPrice": 61422.28861379695
}
]
Even one match comes back in an array because the search handler collects matching records. The parameter is named coinName, yet the server compares it with both the name and the symbol. An empty query gets HTTP 400. A supplied term with no matching record gets HTTP 404. A reader handling both cases can distinguish a missing input from a search that the service actually carried out. Search handler.
The cost of a short request
The URL suggests a direct lookup. Inside the handler, DynamoDB scans the table and returns the four selected fields. The server encodes those records as JSON, immediately decodes them into a Go slice, walks the slice looking for a match, and encodes the matching records again. A small table makes that path easy to follow. It also makes the round trip through JSON easy to overlook. I would have the search handler filter the slice returned by DumpDB and reserve the encoder for the HTTP response.
There is a second limit in the database call. A DynamoDB scan can return one page and a key indicating where to continue. The coursework implementation makes one scan. If the table ever grows beyond that first page, the handler could return 404 for a coin that exists on the next one. A repeatable check would load enough records to force pagination, pick a symbol from the second page, and look it up through the public route. DynamoDB scan pagination.
When the name is almost right
A small input matrix exposes a detail that a successful BTC lookup hides. Given the Bitcoin fixture, Bitcoin, bitcoin, and BITCOIN all match. bItCoIn misses. The handler builds the lowercase and uppercase forms of the stored name and compares each with the query as submitted. That happens to accept the spellings people are likeliest to try. A mixed-case query makes the difference between this implementation and a truly case-insensitive comparison visible.
A second example concerns the shape of the result. Imagine a record with the name and symbol both set to EXAMPLE. Searching for that word would append the record twice. The name and symbol are tested by separate conditions, and each condition appends a match. One route-level check with that invented record would justify a small change to the loop. Test whether either field matches, then append the record once. The sample is deliberately artificial because a successful Bitcoin lookup cannot reveal the duplicate.
These examples also clarify the response format. A script consuming the route needs to check the status before parsing the body. Success gets a JSON array, including the brackets around a single match. The two error branches send text with an HTML content type. Trying to decode that text into a slice produces a parsing error that obscures the more informative HTTP 400 or 404. I would keep those status codes and give every response from the route a documented representation. Name matching and HTTP responses.
How old is the answer?
Consider an upstream response containing a perfectly valid JSON error object and no listings. The collector has a two-second HTTP client timeout, but a server can return an error response well inside that deadline. The fetch path reads the body and proceeds to decode it without branching on the HTTP status. When the data slice is empty, the write loop has no items to refresh. A stored Bitcoin record could still produce a convincing reply afterward. A check on the refresh operation should therefore capture the provider’s status and the number of records accepted as well as the time it took. Upstream request and decoding path.
The collector sleeps for six hours before each fetch, including the first. It then writes one coin at a time. A request arriving midway through a refresh can therefore see records from different polls. The status route reports the table name and item count, and the stored quote has no collection time. A successful BTC lookup establishes that a record exists. To let a reader judge its age, I would store the observation time beside the price and return both. That one field would answer a question no amount of decimal precision can settle.