Home > Net >  how to fetch data from another api with body raw json
how to fetch data from another api with body raw json

Time:12-19

i have default body raw json and want to paste it into a struct so it can fetch data automatically and save it into a struct

Body Raw Json

 {
    "jsonrpc": "2.0",
    "params": {
    }
}

Response from api

{
"jsonrpc": "2.0",
"id": null,
"result": {
    "status": 200,
    "response": [
        {
            "service_id": 1129,
            "service_name": "Adobe Illustrator",
            "service_category_id": 28,
            "service_category_name": "License Software",
            "service_type_id": 25,
            "service_type_name": "Software",
            "create_date": "2020-03-09 03:47:44"
        },
],
    "message": "Done All User Returned"
}

}

I want to put it in the repository file so I can get data automatically

Repo file

// Get request
resp, err := http.Get("look at API Response Example")
if err != nil {
    fmt.Println("No response from request")
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) // response body is []byte
if err != nil {
    return err
}

// data that already fetch accomadate to struct  
var result models.OdooRequest
if err := json.Unmarshal(body, &result); err != nil {  
    fmt.Println("Can not unmarshal JSON")
}

for _, rec := range result.Response {
    fmt.Println(rec.ServiceName)
}
return err

after being fetched then accommodated into a struct

struct

type OdooRequest struct {
    Response []UpsertFromOdooServices
}

CodePudding user response:

Sure, here's a rough way to make that request and read the response:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

type OdooRequest struct {
    Result struct {
        Status   int `json:"status"`
        Response []struct {
            ServiceID           int    `json:"service_id"`
            ServiceName         string `json:"service_name"`
            ServiceCategoryID   int    `json:"service_category_id"`
            ServiceCategoryName string `json:"service_category_name"`
            ServiceTypeID       int    `json:"service_type_id"`
            ServiceTypeName     string `json:"service_type_name"`
            CreateDate          string `json:"create_date"`
        } `json:"response"`
        Message string `json:"message"`
    } `json:"result"`
}

func main() {
    if err := run(); err != nil {
        panic(err)
    }
}
func run() error {
    resp, err := http.Post(
        "ADD_URL_HERE",
        "application/json",
        bytes.NewBufferString(`{"jsonrpc": "2.0","params": {}}`),
    )
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    var odooResp OdooRequest
    if err := json.NewDecoder(resp.Body).Decode(&odooResp); err != nil {
        return err
    }
    for _, rec := range odooResp.Result.Response {
        fmt.Println(rec.ServiceName)
    }
    return nil
}

  •  Tags:  
  • go
  • Related