Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A Brief Introduction to Make an API Client in Go

Riki Makita
November 24, 2021

A Brief Introduction to Make an API Client in Go

Riki Makita

November 24, 2021
Tweet

More Decks by Riki Makita

Other Decks in Programming

Transcript

  1. A Brief Introduction to Write an API Client in Go

    What I learned through implementing github.com/grezar/go-circleci
  2. About Me Makita Riki マキタ リキ Working at Money Forward,

    Inc. Infrastructure Engineer (?) Twitter: @grezarjp GitHub: @grezar
  3. I Wrote CircleCI API Client in Go The official account

    tweeted about my project ✌ https://github.com/grezar/go-circleci
  4. 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
  5. • 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 せやかて
  6. 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 {}
  7. 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
  8. 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
  9. Interface Method (type users struct {} implements Users interface) GetUser

    builds an API request using newRequest and calls the API using do