RESTful Web API Basics in Go

ArticlesBlog

Written by:


Hello and welcome to a little crash course
about RESTful Web API Basics in Go. I am Christoph Berger, and in this video we
will look into REST basics and how to build a tiny REST server in Go. This course consists of two parts. First, we’ll have a brief look at the basics
of RESTful Web API’s. After that, we’ll build a tiny REST server
together. Before touching any code, let’s have a closer
look at the concepts behind REST. REST is an architectural paradigm that can
be seen as an abstraction of the structure and behavior of the World Wide Web. Just like a human clicks a hyperlink and gets
a new page of data back, a REST client sends a request to a server and gets a response
back. The REST protocol is based on four basic operations:
Create, Read, Update, and Delete. These operations are often described by the
acronym CRUD. REST is often but not always based on the
Hypertext Transfer Protocol. Methods are built from HTTP verbs like GET,
POST, PUT, DELETE, et cetera. URL’s just point to resources that the methods
can operate on. A URL never includes a method name. This is how the CRUD operations can be mapped
onto HTTP verbs: Create is mapped to HTTP POST. Read is mapped to GET,
Update to PUT, and Delete to DELETE. This assignment is not absolute. For example, both PUT and POST could be used
to create or update data. In RESTful Web API’s, a URL can describe
a collection of elements, or an individual element. An HTTP verb may therefore represent two different
operations, depending on whether the resource is a collection or a single element. For sending data to the server, there are
two options. First, you can send small amounts of data
within the URL itself. Second, data can reside in the body of the
HTTP request. The server always returns data via the body
of the HTTP response. Coincidentally, database operations also follow
the CRUD scheme: Create maps to SQL INSERT,
Read maps to SELECT, Update to UPDATE, and
Delete to DELETE. Well, ok, this is perhaps not much of a coincidence at all. But anyway, this is a straightforward way
of making database operations accessible to Web clients. Our code consists of standard Go, except for the HTTP router. The standard ServerMux router is very simplistic and provides no path variables nor any complex pattern matching A better choice is httprouter. httprouter provides path variables, designated by a leading colon, as well as a simple way of mapping HTTP verbs to CRUD operations. Let’s start coding now. First, we need a flag for setting the listening
address. We set the default to port 8080, which is
a common HTTP port for servers with local-only access. Then we need a data store. For our purposes, a simple map from string
to string is completely sufficient. The main function starts by parsing the commandline. The data store gets created as an empty map. Now we can create a new httprouter instance
and add some routes. httprouter provides functions named after
HTTP verbs. So to create a route for HTTP GET, we simply
need to call the GET function and pass a route and a handler function. The first route is /entry followed by a key
variable denoted by a leading colon. The handler function is set to show. We do the same for /list. Note that we use the same handler function
here; we’ll switch functionality within the show function based on the existence of
a key variable. For updating, we need a PUT operation. We want to pass a key and a value to the URL,
so we add two variables to the path. The handler function for this PUT operation
is update. Finally, we just have to start the http Server. We pass the listening address as well as our
router instance. For this demo, let’s keep error handling
simple. log.Fatal prints out an error message and
exits the process. Let’s implement the show function now. Typically, handler functions receive two parameters: A Response Writer, and
a Request object. httprouter handlers receive a third parameter
of type Params. This way, the handler function can access
the key and value variables that have been extracted from the incoming URL. To access these parameters, we call the ByName method, passing the variable name. The show function serves two purposes. If there is no key in the URL, it lists all
entries of the data map. If a key is given, the show function returns
the corresponding value. It does so by simply printing to the ResponseWriter
parameter, which is sufficient for our purposes. The update function has the same signature
as the show function. Updates must pass two variables: a key and
a value. We just need to either add or update the entry
in the data map. Finally, we print the result to the ResponseWriter. On saving, the Editor inserted all import
packages including the httprouter package. After saving, we can run the code locally
by calling go run rest.go Now we can call our server. For this, let’s use curl. Curl is an HTTP client for the command line. By default, it sends GET requests, but the
X parameter lets us create a PUT request instead. First, let’s fill the map with some entries. We do that by sending PUT requests with a
key and a value. Then we can request a list of all entries,
as well as individual entries by name. That’s it for today, thanks for watching,
and happy coding!

8 Replies to “RESTful Web API Basics in Go”

  1. Vitor Queiroz says:

    Hello, im trying to implement the delete method by myself.
    By using the same update function signature, getting the key, and trying to delete it , by using the built in delete function: ( delete(data,k) )
    No success, the program doesnt even compile, it gives me a type error.
    Any chance I can get a tip on how to do this? Thanks for the video!

  2. Adrian B.G. says:

    Very good. I added this video to my learning go playlist Learn GOlang: http://www.youtube.com/playlist?list=PLEXf82oPg5ENWfyWkrRi3myOcwftvLo02

  3. MrChrisMoo says:

    What is flag?

  4. Ashutosh Utpat says:

    Very concise tutorial. Thanks for sharing.

  5. Kepler says:

    Not only did you explain how to implement this design in Go, you always explained REST in a way that is easier to mentally grasp than any other explanation I've seen. Thank you sir.

  6. Julien Kirsch says:

    The German accent is strong with this one ^^

    Great video, well done!

  7. The No One says:

    Big thumbs up … And omg! The vi…

  8. Rajesh Samson says:

    I'm getting this exception
    "Cannot use 'show' (type func(w http.ResponseWriter, r *http.Request, p httprouter.Param)) as type Handle less…
    Inspection info: Reports incompatible types."

    My Code Snippet:

    func main() {

    flag.Parse()

    data = map[string]string{}

    r := httprouter.New()

    r.GET("/entry/:key", show) // Getting exception in this line
    }

    func show(w http.ResponseWriter, r *http.Request, p httprouter.Param) {

    k := p.Key

    if k == "" {

    fmt.Fprintf(w, "Read list: %v", data)

    return

    }

    fmt.Fprintf(w, "Read entry : data[%s] = %s", k, data[k])

    }

Leave a Reply

Your email address will not be published. Required fields are marked *