Slide 1

Slide 1 text

A Brief Introduction to Write an API Client in Go What I learned through implementing github.com/grezar/go-circleci

Slide 2

Slide 2 text

About Me Makita Riki マキタ リキ Working at Money Forward, Inc. Infrastructure Engineer (?) Twitter: @grezarjp GitHub: @grezar

Slide 3

Slide 3 text

I Wrote CircleCI API Client in Go The official account tweeted about my project ✌ https://github.com/grezar/go-circleci

Slide 4

Slide 4 text

Motivation for Writing an HTTP API Client ● Useful, needed ● You can learn basic HTTP related processing in that language (in my case, Go) ● There are many reference implementations

Slide 5

Slide 5 text

You've probably seen code like this... .

Slide 6

Slide 6 text

● Define Config/Client structs and its constructors ● Define a method to build a HTTP request (*http.Request) ● Define a method to make the actual HTTP request and handle its response いい感 じに ● Use above stuffs from the service struct’s methods that correspond 1-to-1 with the actual API endpoints Steps to Make It せやかて

Slide 7

Slide 7 text

Step 1 - type Config/Client struct {}

Slide 8

Slide 8 text

Config is utilized for Client initialization Config has some default values type Config struct {}

Slide 9

Slide 9 text

Client has values that are commonly used each API request Client has some methods for building HTTP request, invoking actual API, etc In my (and some other library’s) design, it constructs with the various services to access different parts of the API type Client struct {}

Slide 10

Slide 10 text

Step 2 - A Method Creates an API Request // newRequest creates an API request with proper headers and serializations. // If v is supplied, the value will be JSON encoded and included as the request body. // If the method is GET, it will be query parameters instead. Ref: https://github.com/grezar/go-circleci/blob/c8fca9c02dd337074caeec2515c8f97635597c57/circleci.go#L115-L165

Slide 11

Slide 11 text

Step 3 - A Method Invokes Actual API // do invokes an actual API using req and if v is supplied, fill it with with the API // response deserialized. // It returns error instead, if it gets an error from the API. Ref: https://github.com/grezar/go-circleci/blob/c8fca9c02dd337074caeec2515c8f97635597c57/circleci.go#L167-L2 04

Slide 12

Slide 12 text

Step 4 - Interfaces and Methods

Slide 13

Slide 13 text

Client and Interfaces Interfaces represent various services of the API They are embedded in the Client

Slide 14

Slide 14 text

Interface and Methods Each interface has methods corresponding to each API endpoint

Slide 15

Slide 15 text

Interface Method (type users struct {} implements Users interface) GetUser builds an API request using newRequest and calls the API using do

Slide 16

Slide 16 text

Thank you for listening