Creating RESTful API using Go, Swagger and MongoDB
The purpose of this simple example is to show how to use Swagger to create RESTful API. In this case, written in Go, which uses MongoDB as a storage. Also, the project can be run as a service with Docker through a simple command
Dependencies
You need Go Lang installed. This can be done from here:
https://golang.org/doc/install
You need MongoDB
Instructions can be found here:
https://docs.mongodb.com/manual/installation
The project depends on Dep for packaging, you can install it from here:
https://golang.github.io/dep/docs/installation.html
*note If you decide to use Docker this section is unnecessary.
Install the project by:
$ go get gitlab.com/Cryptle/hetaskapi
$ cd $GOPATH/src/gitlab.com/Cryptle/hetaskapi
Use Dep to update your dependencies:
$ dep ensure
*note Database and server settings are located into config.json file
To regenerate api files from swagger you can do:
$ go generate
To build the project:
$ go build -o heuserapi gitlab.com/Cryptle/hetaskapi/hetaskapi
To run all test cases run:
$ go test -v ./tests/
*note The server must be running when you run the tests because the tests cover live queries against the API
For different test host name change TEST_HOST constant from ./tests/test_common.go
Config file
You can change port, database name and host from config.json
You can use curl to make requests
By default program use http://localhost:5000
To get list of all users
$ curl -X GET "http://{HOST}/users" -H "application/json"
To add new user
$ curl -X POST "http://{HOST}/user/add" -H "application/json" -H "Content-Type: application/json" -d "{ \"email\": \"string\", \"givenName\": \"string\", \"familyName\": \"string\"}"
To get user by ID
$ curl -X GET "http://{HOST}/user/{ID}" -H "application/json"
To Update user
$ curl -X PUT "http://{HOST}/user/{ID}" -H "application/json" -H "Content-Type: application/json" -d "{ \"email\": \"string\", \"givenName\": \"string\", \"familyName\": \"string\"}"
To Delete user
$ curl -X DELETE "http://{HOST}/user/{ID}" -H "application/json"
*note Replace {ID} with existing ID and {HOST} with your host
Using Docker
Dependencies
You need docker and compose to be installed. Use this article to install both them for different platforms:
https://tuleap-documentation.readthedocs.io/en/latest/developer-guide/quick-start/install-docker.html
Or this one, contains installation instructions for Linux:
https://www.digitalocean.com/community/tutorials/how-to-install-docker-compose-on-ubuntu-16-04
You can use Docker to build and start the project. Docker configuration contains two containers, one for MongoDB and one for server.
You need only to start this:
$ docker-compose up -d
To build the containers you can use:
$ docker-compose build --no-cache
After start the server can be found on:
http://localhost:5000/users
For stopping the services you can use:
$ docker-compose stop
An online version can be found here:
http://hx.cryptle.com/users