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.
Start the server:
go run server.go
Create new users:
curl -d "name=jack" \
-d "[email protected]" \
-d "phone=444-444-4444" localhost:4000/users
curl -d "name=jill" \
-d "[email protected]" \
-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":"[email protected]","Phone":"444-444-4444"},{"Id":"0009f23f-d7d3-11e4-8cd5-1093e9029432","Name":"jill","Email":"[email protected]","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": "[email protected]",
"Name": "jack",
"Id": "19ea9175-d7d0-11e4-92b1-1093e9029432"
},
{
"Phone": "555-555-5555",
"Email": "[email protected]",
"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": "[email protected]",
"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": "[email protected]",
"Name": "jill",
"Id": "2e593381-d7d0-11e4-92b1-1093e9029432"
}