Skip to content

A brief rundown on how to generate an API using the go-swagger library

Notifications You must be signed in to change notification settings

taylageben/Go-Swagger-Example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go-Swagger-Example

The following project was generated using the go-swagger library.

For more information on how to customize the generation of and the API itself, see the following documentation.

Getting Started

Before you can generate the API, you need to:

  • Install the Go-Swagger Library
  • Generate a valid Swagger Spec (I used the default 'todo' spec generated by StopLight)

Generating the API

To generate the API, run the following command in your terminal:

$ swagger generate server -f swagger.yml

Modifying the Generated Code

By default, all responses will be generated with a "not yet been implemented" response and will therefore need to be modified to return the correct response(s).

All modifications must take place in the configure file. Any other file will be overwritten if you regenerate the API, unless it's a new file you have added yourself.

Serving the API

To serve the API, run the following command in your terminal:

$ go run cmd/to-do-demo-server/main.go --host=localhost --port=8080

Example Responses

Get Todo

I have implemented this response in the configure file to return a stubbed todo object (See the api.TodosGetTodoHandler = ...)

Request

$ curl -i http://127.0.0.1:8080/todos/1

HTTP/1.1 200 OK
Content-Type: application/json
Date: Thu, 27 Jul 2017 14:05:30 GMT
Content-Length: 162

{"completed":true,"name":"Test","completed_at":"2017-06-24T09:55:54.289Z","created_at":"2017-06-23T09:55:54.289Z","id":1,"updated_at":"2017-06-23T09:55:54.289Z"}

Get Todos

This request requires an api-key to be present in the query. (This is handled in api.ApikeyAuth = ...). The correct response has not yet been implemented.

Request (without the key)

$ curl -i http://127.0.0.1:8080/todos

HTTP/1.1 401 Unauthorized
Content-Type: application/json
Date: Thu, 27 Jul 2017 14:09:23 GMT
Content-Length: 64

{"code":401,"message":"unauthenticated for invalid credentials"}

Request (with the key)

$ curl -i http://127.0.0.1:8080/todos?apikey=123

HTTP/1.1 501 Not Implemented
Content-Type: application/json
Date: Thu, 27 Jul 2017 14:09:41 GMT
Content-Length: 56

"operation todos.GetTodos has not yet been implemented"

About

A brief rundown on how to generate an API using the go-swagger library

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages