block by joyrexus 1e1dcb63b64653229a9e

rest api demo w/ go

Quick demo showing how to to simulate a simple REST API.

Credit where due: this demo is based on this example from Ardan Studios’ training materials. We’re using httprouter for routing and added a retrieve handler for retrieving users by ID (/users/:id).

See also this example, reflecting basic practices for designing a REST API.

Usage

Start the server:

go run server.go

Create new users:

curl -d "name=jack"          \
     -d "email=jack@foo.org" \
     -d "phone=444-444-4444" localhost:4000/users

curl -d "name=jill"          \
     -d "email=jill@foo.org" \
     -d "phone=555-555-5555" localhost:4000/users

… or just run the attached post.sh script to avoid all that typing:

$ . post.sh 
creating jack ...
creating jill ...
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 31 Mar 2015 18:23:16 GMT
Content-Length: 214

[{"Id":"0006bc90-d7d3-11e4-8cd5-1093e9029432","Name":"jack","Email":"jack@foo.org","Phone":"444-444-4444"},{"Id":"0009f23f-d7d3-11e4-8cd5-1093e9029432","Name":"jill","Email":"jill@foo.org","Phone":"555-555-5555"}]

List users:

curl -i localhost:4000/users | jq .

The -i flag indicates we want to see the response header as well, so we should get something like …

HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 31 Mar 2015 17:07:04 GMT
Content-Length: 116
[
  {
    "Phone": "444-444-4444",
    "Email": "jack@foo.org",
    "Name": "jack",
    "Id": "19ea9175-d7d0-11e4-92b1-1093e9029432"
  },
  {
    "Phone": "555-555-5555",
    "Email": "jill@foo.org",
    "Name": "jill",
    "Id": "2e593381-d7d0-11e4-92b1-1093e9029432"
  }
]

Retrieve a user by ID:

curl localhost:4000/users/19ea9175-d7d0-11e4-92b1-1093e9029432
  {
    "Phone": "444-444-4444",
    "Email": "jack@foo.org",
    "Name": "jack",
    "Id": "19ea9175-d7d0-11e4-92b1-1093e9029432"
  }

Search for a user by name:

curl localhost:4000/search?q=jill
  {
    "Phone": "555-555-5555",
    "Email": "jill@foo.org",
    "Name": "jill",
    "Id": "2e593381-d7d0-11e4-92b1-1093e9029432"
  }

post.sh

server.go