{"id":13414014,"url":"https://github.com/huandu/facebook","last_synced_at":"2025-05-13T19:04:05.922Z","repository":{"id":4107405,"uuid":"5216913","full_name":"huandu/facebook","owner":"huandu","description":"A Facebook Graph API SDK For Go.","archived":false,"fork":false,"pushed_at":"2025-03-14T02:56:38.000Z","size":409,"stargazers_count":1369,"open_issues_count":0,"forks_count":534,"subscribers_count":132,"default_branch":"master","last_synced_at":"2025-04-28T00:34:24.572Z","etag":null,"topics":["batch","facebook","go","graph-api","sdk"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/huandu/facebook","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/huandu.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-07-28T19:05:56.000Z","updated_at":"2025-04-25T13:25:32.000Z","dependencies_parsed_at":"2023-07-05T21:32:27.944Z","dependency_job_id":"60b4a4f6-4835-4f1d-97fb-9ed50bbf1cc6","html_url":"https://github.com/huandu/facebook","commit_stats":{"total_commits":186,"total_committers":36,"mean_commits":5.166666666666667,"dds":0.4086021505376344,"last_synced_commit":"38d95ed0de31a8fde36ee0def4dac98bc4b79144"},"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huandu%2Ffacebook","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huandu%2Ffacebook/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huandu%2Ffacebook/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huandu%2Ffacebook/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/huandu","download_url":"https://codeload.github.com/huandu/facebook/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254010796,"owners_count":21998993,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["batch","facebook","go","graph-api","sdk"],"created_at":"2024-07-30T20:01:55.234Z","updated_at":"2025-05-13T19:04:05.902Z","avatar_url":"https://github.com/huandu.png","language":"Go","funding_links":[],"categories":["Repositories","Third-party APIs","Go","第三方API`第三方API 汇总`","第三方api","第三方 APIs","第三方API","\u003cspan id=\"第三方api-third-party-apis\"\u003e第三方API Third-party APIs\u003c/span\u003e","Utility"],"sub_categories":["Utility/Miscellaneous","查询语","实用程序/Miscellaneous","高級控制台界面","HTTP Clients","Advanced Console UIs","交流","Fail injection","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e","高级控制台界面"],"readme":"# A Facebook Graph API SDK In Golang\n\n[![Build Status](https://github.com/huandu/facebook/workflows/Go/badge.svg)](https://github.com/huandu/facebook/actions)\n[![GoDoc](https://godoc.org/github.com/huandu/facebook?status.svg)](https://pkg.go.dev/github.com/huandu/facebook/v2)\n\nThis is a Go package that fully supports the [Facebook Graph API](https://developers.facebook.com/docs/graph-api/) with file upload, batch request and marketing API. It can be used in Google App Engine.\n\nAPI documentation can be found on [godoc](https://pkg.go.dev/github.com/huandu/facebook/v2).\n\nFeel free to create an issue or send me a pull request if you have any \"how-to\" question or bug or suggestion when using this package. I'll try my best to reply to it.\n\n## Install\n\nIf `go mod` is enabled, install this package with `go get github.com/huandu/facebook/v2`. If not, call `go get -u github.com/huandu/facebook` to get the latest master branch version.\n\nNote that, since go1.14, [incompatible versions are omitted](https://golang.org/doc/go1.14#incompatible-versions) unless specified explicitly. Therefore, it's highly recommended to upgrade the import path to `github.com/huandu/facebook/v2` when possible to avoid any potential dependency error.\n\n## Usage\n\n### Quick start\n\nHere is a sample that reads my Facebook first name by uid.\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    fb \"github.com/huandu/facebook/v2\"\n)\n\nfunc main() {\n    res, _ := fb.Get(\"/538744468\", fb.Params{\n        \"fields\": \"first_name\",\n        \"access_token\": \"a-valid-access-token\",\n    })\n    fmt.Println(\"Here is my Facebook first name:\", res[\"first_name\"])\n}\n```\n\nThe type of `res` is `fb.Result` (a.k.a. `map[string]interface{}`).\nThis type has several useful methods to decode `res` to any Go type safely.\n\n```go\n// Decode \"first_name\" to a Go string.\nvar first_name string\nres.DecodeField(\"first_name\", \u0026first_name)\nfmt.Println(\"Here's an alternative way to get first_name:\", first_name)\n\n// It's also possible to decode the whole result into a predefined struct.\ntype User struct {\n    FirstName string\n}\n\nvar user User\nres.Decode(\u0026user)\nfmt.Println(\"print first_name in struct:\", user.FirstName)\n```\n\nIf a type implements the `json.Unmarshaler` interface, `Decode` or `DecodeField` will use it to unmarshal JSON.\n\n```go\nres := Result{\n    \"create_time\": \"2006-01-02T15:16:17Z\",\n}\n\n// Type `*time.Time` implements `json.Unmarshaler`.\n// res.DecodeField will use the interface to unmarshal data.\nvar tm time.Time\nres.DecodeField(\"create_time\", \u0026tm)\n```\n\n### Read a graph `user` object with a valid access token\n\n```go\nres, err := fb.Get(\"/me/feed\", fb.Params{\n     \"access_token\": \"a-valid-access-token\",\n})\n\nif err != nil {\n    // err can be a Facebook API error.\n    // if so, the Error struct contains error details.\n    if e, ok := err.(*Error); ok {\n        fmt.Printf(\"facebook error. [message:%v] [type:%v] [code:%v] [subcode:%v] [trace:%v]\",\n            e.Message, e.Type, e.Code, e.ErrorSubcode, e.TraceID)\n        return\n    }\n\n    // err can be an unmarshal error when Facebook API returns a message which is not JSON.\n    if e, ok := err.(*UnmarshalError); ok {\n        fmt.Printf(\"facebook error. [message:%v] [err:%v] [payload:%v]\",\n            e.Message, e.Err, string(e.Payload))\n        return\n    }\n\n    return\n}\n\n// read my last feed story.\nfmt.Println(\"My latest feed story is:\", res.Get(\"data.0.story\"))\n```\n\n### Read a graph `search` for page and decode slice of maps\n\n```go\nres, _ := fb.Get(\"/pages/search\", fb.Params{\n        \"access_token\": \"a-valid-access-token\",\n        \"q\":            \"nightlife,singapore\",\n    })\n\nvar items []fb.Result\n\nerr := res.DecodeField(\"data\", \u0026items)\n\nif err != nil {\n    fmt.Printf(\"An error has happened %v\", err)\n    return\n}\n\nfor _, item := range items {\n    fmt.Println(item[\"id\"])\n}\n```\n\n### Use `App` and `Session`\n\nIt's recommended to use `App` and `Session` in a production app. They provide more control over all API calls. They can also make code clearer and more concise.\n\n```go\n// Create a global App var to hold app id and secret.\nvar globalApp = fb.New(\"your-app-id\", \"your-app-secret\")\n\n// Facebook asks for a valid redirect URI when parsing the signed request.\n// It's a newly enforced policy starting as of late 2013.\nglobalApp.RedirectUri = \"http://your.site/canvas/url/\"\n\n// Here comes a client with a Facebook signed request string in the query string.\n// This will return a new session from a signed request.\nsession, _ := globalApp.SessionFromSignedRequest(signedRequest)\n\n// If there is another way to get decoded access token,\n// this will return a session created directly from the token.\nsession := globalApp.Session(token)\n\n// This validates the access token by ensuring that the current user ID is properly returned. err is nil if the token is valid.\nerr := session.Validate()\n\n// Use the new session to send an API request with the access token.\nres, _ := session.Get(\"/me/feed\", nil)\n```\n\nBy default, all requests are sent to Facebook servers. If you wish to override the API base URL for unit-testing purposes - just set the respective `Session` field.\n\n```go\ntestSrv := httptest.NewServer(someMux)\nsession.BaseURL = testSrv.URL + \"/\"\n```\n\nFacebook returns most timestamps in an ISO9601 format which can't be natively parsed by Go's `encoding/json`.\nSetting `RFC3339Timestamps` `true` on the `Session` or at the global level will cause proper RFC3339 timestamps to be requested from Facebook.\nRFC3339 is what `encoding/json` natively expects.\n\n```go\nfb.RFC3339Timestamps = true\nsession.RFC3339Timestamps = true\n```\n\nSetting either of these to true will cause `date_format=Y-m-d\\TH:i:sP` to be sent as a parameter on every request. The format string is a PHP `date()` representation of RFC3339.\nMore info is available in [this issue](https://github.com/huandu/facebook/issues/95).\n\n### Use `paging` field in response\n\nSome Graph API responses use a special JSON structure to provide paging information. Use `Result.Paging()` to walk through all data in such results.\n\n```go\nres, _ := session.Get(\"/me/home\", nil)\n\n// create a paging structure.\npaging, _ := res.Paging(session)\n\nvar allResults []Result\n\n// append first page of results to slice of Result\nallResults = append(allResults, paging.Data()...)\n\nfor {\n  // get next page.\n  noMore, err := paging.Next()\n  if err != nil {\n    panic(err)\n  }\n  if noMore {\n    // No more results available\n    break\n  }\n  // append current page of results to slice of Result\n  allResults = append(allResults, paging.Data()...)\n}\n\n```\n\n### Read Graph API response and decode result in a struct\n\nThe Facebook Graph API always uses snake case keys in API response.\nThis package can automatically convert from snake case to Go's camel-case-style style struct field names.\n\nFor instance, to decode the following JSON response...\n\n```json\n{\n  \"foo_bar\": \"player\"\n}\n```\n\nOne can use the following struct.\n\n```go\ntype Data struct {\n    FooBar string  // \"FooBar\" maps to \"foo_bar\" in JSON automatically in this case.\n}\n```\n\nThe decoding of each struct field can be customized by the format string stored under the `facebook` key or the \"json\" key in the struct field's tag. The `facebook` key is recommended as it's specifically designed for this package.\n\nFollowing is a sample that shows all possible field tags.\n\n```go\n// define a Facebook feed object.\ntype FacebookFeed struct {\n    Id          string            `facebook:\",required\"`             // this field must exist in response.\n                                                                     // mind the \",\" before \"required\".\n    Story       string\n    FeedFrom    *FacebookFeedFrom `facebook:\"from\"`                  // use customized field name \"from\".\n    CreatedTime string            `facebook:\"created_time,required\"` // both customized field name and \"required\" flag.\n    Omitted     string            `facebook:\"-\"`                     // this field is omitted when decoding.\n}\n\ntype FacebookFeedFrom struct {\n    Name string `json:\"name\"`                   // the \"json\" key also works as expected.\n    Id string   `facebook:\"id\" json:\"shadowed\"` // if both \"facebook\" and \"json\" key are set, the \"facebook\" key is used.\n}\n\n// create a feed object direct from Graph API result.\nvar feed FacebookFeed\nres, _ := session.Get(\"/me/feed\", nil)\nres.DecodeField(\"data.0\", \u0026feed) // read latest feed\n```\n\n### Send a batch request\n\n```go\nparams1 := Params{\n    \"method\": fb.GET,\n    \"relative_url\": \"me\",\n}\nparams2 := Params{\n    \"method\": fb.GET,\n    \"relative_url\": uint64(100002828925788),\n}\nresults, err := fb.BatchApi(your_access_token, params1, params2)\n\nif err != nil {\n    // check error...\n    return\n}\n\n// batchResult1 and batchResult2 are response for params1 and params2.\nbatchResult1, _ := results[0].Batch()\nbatchResult2, _ := results[1].Batch()\n\n// Use parsed result.\nvar id string\nres := batchResult1.Result\nres.DecodeField(\"id\", \u0026id)\n\n// Use response header.\ncontentType := batchResult1.Header.Get(\"Content-Type\")\n```\n\n### Using with Google App Engine\n\nGoogle App Engine provides the `appengine/urlfetch` package as the standard HTTP client package.\nFor this reason, the default client in `net/http` won't work.\nOne must explicitly set the HTTP client in `Session` to make it work.\n\n```go\nimport (\n    \"appengine\"\n    \"appengine/urlfetch\"\n)\n\n// suppose it's the AppEngine context initialized somewhere.\nvar context appengine.Context\n\n// default Session object uses http.DefaultClient which is not allowed to use\n// in appengine. one has to create a Session and assign it a special client.\nseesion := globalApp.Session(\"a-access-token\")\nsession.HttpClient = urlfetch.Client(context)\n\n// now, the session uses AppEngine HTTP client now.\nres, err := session.Get(\"/me\", nil)\n```\n\n### Select Graph API version\n\nSee [Platform Versioning](https://developers.facebook.com/docs/apps/versions) to understand the Facebook versioning strategy.\n\n```go\n// This package uses the default version which is controlled by the Facebook app setting.\n// change following global variable to specify a global default version.\nfb.Version = \"v3.0\"\n\n// starting with Graph API v2.0; it's not allowed to get useful information without an access token.\nfb.Api(\"huan.du\", GET, nil)\n\n// it's possible to specify version per session.\nsession := \u0026fb.Session{}\nsession.Version = \"v3.0\" // overwrite global default.\n```\n\n### Enable `appsecret_proof`\n\nFacebook can verify Graph API Calls with `appsecret_proof`. It's a feature to make Graph API call more secure. See [Securing Graph API Requests](https://developers.facebook.com/docs/graph-api/securing-requests) to know more about it.\n\n```go\nglobalApp := fb.New(\"your-app-id\", \"your-app-secret\")\n\n// enable \"appsecret_proof\" for all sessions created by this app.\nglobalApp.EnableAppsecretProof = true\n\n// all calls in this session are secured.\nsession := globalApp.Session(\"a-valid-access-token\")\nsession.Get(\"/me\", nil)\n\n// it's also possible to enable/disable this feature per session.\nsession.EnableAppsecretProof(false)\n```\n\n### Debugging API Requests\n\nFacebook has introduced a way to debug Graph API calls. See [Debugging API Requests](https://developers.facebook.com/docs/graph-api/using-graph-api/debugging) for more details.\n\nThis package provides both a package level and per session debug flag. Set `Debug` to a `DEBUG_*` constant to change debug mode globally, or use `Session#SetDebug` to change debug mode for one session.\n\nWhen debug mode is turned on, use `Result#DebugInfo` to get `DebugInfo` struct from the result.\n\n```go\nfb.Debug = fb.DEBUG_ALL\n\nres, _ := fb.Get(\"/me\", fb.Params{\"access_token\": \"xxx\"})\ndebugInfo := res.DebugInfo()\n\nfmt.Println(\"http headers:\", debugInfo.Header)\nfmt.Println(\"facebook api version:\", debugInfo.FacebookApiVersion)\n```\n\n### Monitoring API usage info\n\nCall `Result#UsageInfo` to get a `UsageInfo` struct containing both app and page-level rate limit information from the result. More information about rate limiting can be found [here](https://developers.facebook.com/docs/graph-api/overview/rate-limiting).\n\n```go\nres, _ := fb.Get(\"/me\", fb.Params{\"access_token\": \"xxx\"})\nusageInfo := res.UsageInfo()\n\nfmt.Println(\"App level rate limit information:\", usageInfo.App)\nfmt.Println(\"Page level rate limit information:\", usageInfo.Page)\nfmt.Println(\"Ad account rate limiting information:\", usageInfo.AdAccount)\nfmt.Println(\"Business use case usage information:\", usageInfo.BusinessUseCase)\n```\n\n### Work with package `golang.org/x/oauth2`\n\nThe `golang.org/x/oauth2` package can handle the Facebook OAuth2 authentication process and access token quite well. This package can work with it by setting `Session#HttpClient` to OAuth2's client.\n\n```go\nimport (\n    \"golang.org/x/oauth2\"\n    oauth2fb \"golang.org/x/oauth2/facebook\"\n    fb \"github.com/huandu/facebook/v2\"\n)\n\n// Get Facebook access token.\nconf := \u0026oauth2.Config{\n    ClientID:     \"AppId\",\n    ClientSecret: \"AppSecret\",\n    RedirectURL:  \"CallbackURL\",\n    Scopes:       []string{\"email\"},\n    Endpoint:     oauth2fb.Endpoint,\n}\ntoken, err := conf.Exchange(oauth2.NoContext, \"code\")\n\n// Create a client to manage access token life cycle.\nclient := conf.Client(oauth2.NoContext, token)\n\n// Use OAuth2 client with session.\nsession := \u0026fb.Session{\n    Version:    \"v2.4\",\n    HttpClient: client,\n}\n\n// Use session.\nres, _ := session.Get(\"/me\", nil)\n```\n\n### Control timeout and cancelation with `Context`\n\nThe `Session` accept a `Context`.\n\n```go\n// Create a new context.\nctx, cancel := context.WithTimeout(session.Context(), 100 * time.Millisecond)\ndefer cancel()\n\n// Call an API with ctx.\n// The return value of `session.WithContext` is a shadow copy of original session and\n// should not be stored. It can be used only once.\nresult, err := session.WithContext(ctx).Get(\"/me\", nil)\n```\n\nSee [this Go blog post about context](https://blog.golang.org/context) for more details about how to use `Context`.\n\n## Change Log\n\nSee [CHANGELOG.md](CHANGELOG.md).\n\n## Out of Scope\n\n1. No OAuth integration. This package only provides APIs to parse/verify access token and code generated in OAuth 2.0 authentication process.\n2. No old RESTful API and FQL support. Such APIs are deprecated for years. Forget about them.\n\n## License\n\nThis package is licensed under the MIT license. See LICENSE for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuandu%2Ffacebook","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuandu%2Ffacebook","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuandu%2Ffacebook/lists"}