• This repository has been archived on 12/Nov/2019
  • Stars
    star
    328
  • Rank 128,352 (Top 3 %)
  • Language
    Go
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[MOVED TO NEW REPO] Golang RESTful API Server Generator

⚠️ This package is now officially maintained by @shimastripe at shimastripe/apig. ⚠️

This repository exists only for preventing existing codes from failing to resolve package, and will no longer be maintained. Please send a pull request to the new repository.


apig: Golang RESTful API Server Generator

Build Status

apig is an RESTful API server generator.

  • Input: Model definitions based on gorm annotated struct
  • Output: RESTful JSON API server using gin including tests and documents

Contents

How to build and install

Go 1.6 or higher is required.

After installing required version of Go, you can build and install apig by

$ go get -d -u github.com/wantedly/apig
$ cd $GOPATH/src/github.com/wantedly/apig
$ make
$ make install

make generates binary into bin/apig. make install put it to $GOPATH/bin.

How to use

1. Generate boilerplate

First, creating by apig new command.

$ apig new -u wantedly apig-sample

generates Golang API server boilerplate under $GOPATH/src/gihhub.com/wantedly/apig-sample. apig supports two database engines; SQLite (sqlite) and PostgreSQL (postgres) and Mysql (mysql). You can specify this by -d, -database option.

Available command line options of apig new command are:

Option Description Required Default
-d, -database Database engine sqlite
-n, -namespace Namespace of API (empty)
-u, -user Username github username
--vcs VCS github.com

2. Write model code

Second, write model definitions under models/. For example, user and email model is like below:

// models/user.go
package models

import "time"

type User struct {
	ID        uint       `gorm:"primary_key;AUTO_INCREMENT" json:"id" form:"id"`
	Name      string     `json:"name" form:"name"`
	Emails    []Email    `json:"emails" form:"emails"`
	CreatedAt *time.Time `json:"created_at" form:"created_at"`
	UpdatedAt *time.Time `json:"updated_at" form:"updated_at"`
}
// models/email.go
package models

type Email struct {
	ID      uint   `gorm:"primary_key;AUTO_INCREMENT" json:"id" form:"id"`
	UserID  uint   `json:"user_id" form:"user_id"`
	Address string `json:"address" form:"address"`
	User    *User  `json:"user form:"user`
}

This models are based on gorm structure. Please refer gorm document to write detailed models.

3. Generate controllers, tests, documents etc. based on models.

Third, run the command:

apig gen

It creates all necessary codes to provide RESTful endpoints of models.

4. Build and run server

Finally, just build as normal go code.

$ go get ./...
$ go build -o bin/server

After that just execute the server binary. For the first time, you may want to use AUTOMIGRATE=1 when running the server.

$ AUTOMIGRATE=1 bin/server

When AUTOMIGRATE=1, the db tables are generated automatically. After that, you can run the server just executing the command:

$ bin/server

The server runs at http://localhost:8080.

By default, use the port 8080. If you change the port, set environment variables.

$ PORT=3000 bin/server

The server runs at http://localhost:3000.

Usage

new command

new command tells apig to generate API server skeleton.

$ apig new NAME

gen command

gen command tells apig to generate files (routes, controllers, documents...) from gorm model files you wrote.

You MUST run this command at the directory which was generated by new command.

$ apig gen

API Document

API Documents are generated automatically in docs/ directory in the form of API Blueprint.

docs
├── email.apib
├── index.apib
└── user.apib

Aglio is an API Blueprint renderer. Aglio can be installed by

$ npm install -g aglio

You can generate HTML files and run live preview server.

// html file
$ aglio -i index.apib  -o index.html

// running server on localhost:3000
$ aglio -i index.apib --server

index.apib includes other files in your blueprint.

API server specification

Endpoints

Each resource has 5 RESTful API endpoints. Resource name is written in the plural form.

Endpoint Description Example (User resource)
GET /<resources> List items GET /users List users
POST /<resources> Create new item POST /users Create new user
GET /<resources>/{id} Retrieve the item GET /users/1 Get the user which ID is 1
PUT /<resources>/{id} Update the item PUT /users/1 Update the user which ID is 1
DELETE /<resources>/{id} Delete the item DELETE /users/1 Delete the user which ID is 1

Available URL parameters

GET /<resources> and GET /<resources>/{id}

Parameter Description Default Example
fields= Fields to receive All fields name,emails.address
preloads= Nested resources to preload (empty) emails,profile
pretty= Prettify JSON response false true

GET /<resources> only

Parameter Description Default Example
stream= Return JSON in streaming format false true
q[field_name]= A unique query parameter for each field for filtering (empty) q[id]=1,2,5, q[admin]=true&q[registered]=true
sort= Retrieves a list in order of priority. + or (none) : ascending. - : descending (empty) id, -age, id,-created_at
limit= Maximum number of items 25 50
page= Page to receive 1 3
last_id= Beginning ID of items (empty) 1
order= Order of items desc asc
v= API version (empty) 1.2.0

Data Type

Request

API server accepts the form of JSON or Form.

application/json

curl -X POST http://localhost:8080/resources \
     -H "Content-type: application/json" \
     -d '{"field":"value"}'

application/x-www-form-urlencoded

curl -X POST http://localhost:8080/users \
     -d 'field=value'

multipart/form-data

curl -X POST http://localhost:8080/users \
     -F 'field=value'

Response

Response data type is always application/json.

Pagination

API server supports 2 pagination types.

Offset-based pagination

Retrieve items by specifying page number and the number of items per page.

For example:

http://example.com/api/users?limit=5&page=2
+---------+---------+---------+---------+---------+---------+---------+
| ID: 5   | ID: 6   | ID: 7   | ID: 8   | ID: 9   | ID: 10  | ID: 11  |
+---------+---------+---------+---------+---------+---------+---------+
          |                                                 |
 Page 1 ->|<-------------------- Page 2 ------------------->|<- Page 3

Response header includes Link header.

Link:   <http://example.com/api/users?limit=5&page=3>; rel="next",
        <http://example.com/api/users?limit=5&page=1>; rel="prev"

ID/Time-based pagination

Retrieve items by specifying range from a certain point.

For example:

http://example.com/api/users?limit=5&last_id=100&order=desc
+---------+---------+---------+---------+---------+---------+---------+
| ID: 94  | ID: 95  | ID: 96  | ID: 97  | ID: 98  | ID: 99  | ID: 100 |
+---------+---------+---------+---------+---------+---------+---------+
          |               5 items (ID < 100)                |
          |<------------------------------------------------|

Response header includes Link header.

Link:   <http://example.com/api/users?limit=5&last_id=95&order=desc>; rel="next"

Versioning

API server uses Semantic Versioning for API versioning.

There are 2 methods to specify API version.

Request header

Generally we recommend to include API version in Accept header.

Accept: application/json; version=1.0.0

URL parameter

You can also include API version in URL parameter. This is userful for debug on browser or temporary use,

http://example.com/api/users?v=1.0.0

This method is prior to request header method.

License

MIT License

More Repositories

1

swift-rss-sample

An RSS reader app written in Swift
Swift
461
star
2

machine-learning-round-table

Gather around the table, and have a discussion to catch up the latest trend of machine learning 🤖
305
star
3

learning-resources

エンジニア向け教材集
222
star
4

nginx-image-server

Dockerfile for Dynamic Image Transformation Server with Nginx and Small Light module
Ruby
156
star
5

step-pretty-slack-notify

Posts wercker build/deploy status to a Slack channel
Ruby
88
star
6

hi18n

message internationalization meets immutability and type-safety
TypeScript
88
star
7

react-declassify

say goodbye to class components
TypeScript
85
star
8

subee

✉️ 🐝 It's not only a bee, but a message - Pub/Sub Worker Framework Implementation
Go
48
star
9

proto-graphql-rust

[EXPERIMENTAL] Generate GraphQL schema and gateway from Proto definitions.
Rust
34
star
10

recsys2020-challenge

Python
32
star
11

microservices_monday

Monday is a good day to talk about Microservices
31
star
12

gorm-zap

Alternative logging with zap for GORM ⚡️
Go
30
star
13

iosdc2018-reactorkit

iOSDC2018 ReactorKitで作る実践iOS App
Swift
29
star
14

frolint

Frontend linter for developers
TypeScript
28
star
15

dockertags

Retrieve available Docker image tag list from image repository
Go
27
star
16

the_pb

Utility for Google Protocol Buffers
Ruby
26
star
17

pq2gorm

Generate gorm model structs from PostgreSQL database schema
Go
25
star
18

computed_model

Batch loader with dependency resolution and computed fields
Ruby
25
star
19

grpc_access_logging_interceptor

An interceptor for access logging with gRPC.
Ruby
19
star
20

ios_night

Let's talk about iOS development -- iOS Night 📱🌙 You might apply to this meetup from
18
star
21

frontend-night

Tuesday is a good day to talk about Frontend
17
star
22

grpc_opencensus_interceptor

An interceptor for using OpenCensus with gRPC.
Ruby
16
star
23

grpc_newrelic_interceptor

An interceptor for using New Relic with gRPC.
Ruby
16
star
24

pb-serializer

Serialize Ruby objects to Protocol Buffers
Ruby
15
star
25

intern-info

Wantedlyのインターン情報や新卒採用についてのインフォメーションです
12
star
26

psych-comments

Brings comment-aware parsing to Psych, Ruby's YAML parser
Ruby
12
star
27

open_api_annotator

OpenAPI spec generation by bottom-up.
Ruby
11
star
28

kubefork-controller

Go
11
star
29

aws-es-auth-proxy

Authentication Proxy for Amazon Elasticsearch Service
11
star
30

gcpc

Google Cloud Pub/Sub client for Ruby
Ruby
11
star
31

grpc-gateway-study

sample code for grpc-gateway study #grpc_gateway_wt
Shell
10
star
32

open_api

Provide PORO and serializers for OpenAPI v3.0.1
Ruby
9
star
33

canary-controller

Custom Resource and Controller for managing Canary server.
Go
9
star
34

kubernetes-code-reading-party

Kubernetes 読書会
8
star
35

kong-on-kubernetes

Shell
6
star
36

apiblueprint-rails

apiblueprint-rails creates API Blueprint boilerplate when calling 'rails g apiblueprint'.
Ruby
6
star
37

raycast-dev-docs

TypeScript
6
star
38

sketch-wt-design

[Deprecated] Sketch plugin for Wantedly Design System
JavaScript
6
star
39

ctmcp-reading

Reading: "Concepts, Techniques, and Models of Computer Programming"
5
star
40

boilerplate

[deprecated] 新しいサービス用のレポジトリを作るときに模範にしてもらいたい構成
Ruby
5
star
41

grpc_typechecker

A dynamic type checker for gRPC methods
Ruby
4
star
42

dockerfile-locust

Docker Image packaging for locust
Dockerfile
4
star
43

developers-account-mapper

Convert a username to other account usernames associated with the user.
Go
4
star
44

deployment-duplicator

Go
4
star
45

wantedly.github.io

Wantedly Engineer Blog (retired)
HTML
4
star
46

ev-cli

CLI tool for managing evaluation data
Go
3
star
47

grpc_server

Simple utility class for using gRPC server
Ruby
3
star
48

activerecord-lookml

[Experimental] ActiveRecord extension for LookML (Looker)
Ruby
3
star
49

dockerfile-terraform

Docker image packaging for Terraform
Ruby
3
star
50

Cerberus

📅 Our room keeper
Swift
3
star
51

opencensus-datadog

Ruby
3
star
52

omniauth-wantedly

Wantedly OAuth2 Strategy for OmniAuth gem.
Ruby
3
star
53

gophers-code-reading-party

ʕ ◔ϖ◔ʔ
2
star
54

k8nskel

Kubernetes Controller to distribute Secrets to new Namespace on Kubernetes.
Go
2
star
55

shisucon2019-teppei-haruki

SHInsotsu iSUCON
Ruby
2
star
56

fmparser

FieldMask parameter parser
Ruby
2
star
57

webmock-proxy

Go
2
star
58

dockerfile-crontab-docker

Docker Image for crontab + Docker
Ruby
2
star
59

hands-on-native-esm-2022

Hands-on Native ESM @ JSConf JP 2022
JavaScript
2
star
60

docker-dd-trace-agent

Datadog agent for trace agent
1
star
61

refineimg

Go
1
star
62

dockerfile-sidekiq-prometheus-exporter

Dockerfile for sidekiq-prometheus-exporter
Ruby
1
star
63

kubedeploy

Display and update images of Kubernetes deployment
Go
1
star
64

grpcutil

Utilities of gRPC server / client for Golang
Go
1
star
65

private-isucon-2018-kobayang-bgpat

HTML
1
star
66

rigger

Custom Resource and Controller to collect Secrets from all Namespaces and sync to specific Namespace.
Go
1
star
67

istio-ruby

Ruby gem for Istio service mesh (https://istio.io/)
Ruby
1
star
68

kong-frontend

Go
1
star
69

angular-notification-banner

angular notification banner
JavaScript
1
star
70

reloader_interceptor

A gRPC interceptor for using ActiveSupport::Reloader.
Ruby
1
star
71

graphql-server-for-selection

フロントエンドエンジニア採用の技術選考用のサンプルGraphQLサーバー
TypeScript
1
star
72

apib-sample

0512 API Blueprint速習会
Ruby
1
star