linkedin

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2025 License: MIT Imports: 8 Imported by: 0

README

LinkedIn API Go Client

CodeQL Linter Go Reference Go Report Card MIT license

This Go package provides a thin client for making requests to LinkedIn APIs following the official LinkedIn API documentation.

⚠ This API client package is currently in beta and is subject to change. It may contain bugs, errors, or other issues that we are working to resolve. Use of this package is at your own risk. Please use caution when using it in production environments and be prepared for the possibility of unexpected behavior. We welcome any feedback or reports of issues that you may encounter while using this package.

Versioning

x.y.z

  • x:
    • 0: under development
    • 1: production-ready
  • y: breaking changes
  • z: new functionality or bug fixes in a backwards compatible manner

Requirement

Go 1.19+

Features

  • [x]: Supports Rest.li protocol version 2.0.0
  • [x]: Supports LinkedIn versioned APIs
  • [x]: 2-legged and 3-legged OAuth2 support
  • [x]: Fine-grained control over all API calls using App and Session
  • [x]: Extensive documentation and examples

References

License

© Mahir Hasan 2024 - 2025.

Released under the MIT license

Documentation

Overview

Package linkedin provides a thin client for making requests to LinkedIn APIs following the official LinkedIn API documentation.

Index

Constants

View Source
const (
	OauthBaseURL     = "https://www.linkedin.com/oauth/v2"
	VersionedBaseURL = "https://api.linkedin.com/rest"
)

LinkedIn rest api base urls

See: https://learn.microsoft.com/en-us/linkedin/marketing/versioning?view=li-lms-2024-04

View Source
const (
	ListPrefix       = "List("
	ListSuffix       = ")"
	ListItemSep      = ","
	ObjPrefix        = "("
	ObjSuffix        = ")"
	ObjKeyValSep     = ":"
	ObjKeyValPairSep = ","
	LeftBracket      = "("
	RightBracket     = ")"
)

Rest.Li special characters

Variables

RestLiMethodToHTTPMethodMap - map of LinkedIn Rest.Li methods to HTTP methods

Functions

func DecodeURL added in v0.1.1

func DecodeURL(text string) (string, error)

DecodeURL decodes URL-encoded text into plain text

func EncodeURL added in v0.1.1

func EncodeURL(text string) string

EncodeURL encodes text into URL-encoded format

Types

type App

type App struct {
	ClientID     string
	ClientSecret string
	RedirectURI  string
	// contains filtered or unexported fields
}

App holds the configuration for the LinkedIn application.

ClientID and ClientSecret: https://www.linkedin.com/developers/apps/{appID}/auth

func New

func New(clientID, clientSecret string) *App

New creates a new LinkedIn application and sets clientID and clientSecret.

func (*App) ParseCode

func (app *App) ParseCode(code string) (Token, error)

ParseCode redeems authorization code for access and refresh tokens.

See https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin%2Fcontext&tabs=HTTPS1

func (*App) RefreshToken added in v0.1.2

func (app *App) RefreshToken(refreshToken string) (Token, error)

RefreshToken redeems refresh token for new access and refresh tokens.

See: https://learn.microsoft.com/en-us/linkedin/shared/authentication/programmatic-refresh-tokens?toc=%2Flinkedin%2Fmarketing%2Ftoc.json&bc=%2Flinkedin%2Fbreadcrumb%2Ftoc.json&view=li-lms-2024-04

func (*App) Session

func (app *App) Session(accessToken string) *Session

Session creates a new LinkedIn session based on the app configuration.

type ContentDataType

type ContentDataType string

ContentDataType - HTTP content data type

const (
	URLEncoded ContentDataType = "application/x-www-form-urlencoded"
	JSON       ContentDataType = "application/json"
)

HTTP content data type

type CoverPhotoV2 added in v0.1.1

type CoverPhotoV2 struct {
	Original string `json:"original"`
}

CoverPhotoV2 struct for cover photo

type Created added in v0.1.1

type Created struct {
	Actor        string `json:"actor"`        // e.g. urn:li:person:a1b2c3
	Impersonator string `json:"impersonator"` // e.g. urn:li:servicePrincipal:organization
	Time         int64  `json:"time"`         // e.g. 1612345678901
}

Created struct for created timestamp

type DefaultLocale added in v0.1.1

type DefaultLocale struct {
	Country  string `json:"country"`  // e.g. US
	Language string `json:"language"` // e.g. en
}

DefaultLocale struct for default locale

type DistributionPost added in v0.1.1

type DistributionPost struct {
	FeedDistribution string `json:"feedDistribution"` // e.g. MAIN_FEED
}

DistributionPost struct for LinkedIn post distribution

type ElementOrganization added in v0.1.1

type ElementOrganization struct {
	RoleAssignee string       `json:"roleAssignee"` // e.g. urn:li:person:a1b2c3
	State        string       `json:"state"`        // e.g. APPROVED
	LastModified LastModified `json:"lastModified"`
	Role         string       `json:"role"` // e.g. ADMINISTRATOR
	Created      Created      `json:"created"`
	Organization string       `json:"organization"` // e.g. urn:li:organization:123456789
}

ElementOrganization struct for LinkedIn organization elements

func (*ElementOrganization) GetOrganizationID added in v0.1.1

func (e *ElementOrganization) GetOrganizationID() string

GetOrganizationID returns the organization ID from the organization URN

type ElementPost added in v0.1.1

type ElementPost struct {
	IsReshareDisabledByAuthor bool                   `json:"isReshareDisabledByAuthor"`
	CreatedAt                 int64                  `json:"createdAt"`
	LifecycleState            string                 `json:"lifecycleState"` // e.g. PUBLISHED
	LastModifiedAt            int64                  `json:"lastModifiedAt"`
	Visibility                string                 `json:"visibility"` // e.g. PUBLIC
	PublishedAt               int64                  `json:"publishedAt"`
	Author                    string                 `json:"author"` // e.g. urn:li:organization:123456
	ID                        string                 `json:"id"`     // e.g. urn:li:ugcPost:123456
	ReshareContext            ReshareContextPost     `json:"reshareContext"`
	Distribution              DistributionPost       `json:"distribution"`
	Commentary                string                 `json:"commentary"` // e.g. Hello, world!
	LifecycleStateInfo        LifecycleStateInfoPost `json:"lifecycleStateInfo"`
}

ElementPost struct for LinkedIn post elements

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (resp *http.Response, err error)
	Get(url string) (resp *http.Response, err error)
	Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error)
}

HTTPClient is an interface to send http request. It is compatible with type `*http.Client`.

type Header string

Header - HTTP header data type

const (
	ContentType           Header = "Content-Type"
	Connection            Header = "Connection"
	RestLiProtocolVersion Header = "X-RestLi-Protocol-Version"
	RestLiMethodHeader    Header = "X-RestLi-Method"
	LinkedInVersion       Header = "LinkedIn-Version"
	Authorization         Header = "Authorization"
	UserAgent             Header = "user-agent"
	CreatedEntityID       Header = "X-RestLi-Id"
)

HTTP headers used in LinkedIn API requests

https://linkedin.github.io/rest.li/spec/protocol

https://learn.microsoft.com/en-us/linkedin/marketing/versioning?view=li-lms-2024-04#how-your-api-client-should-use-versioning

type LastModified added in v0.1.1

type LastModified struct {
	Actor        string `json:"actor"`        // e.g. urn:li:person:a1b2c3
	Impersonator string `json:"impersonator"` // e.g. urn:li:servicePrincipal:organization
	Time         int64  `json:"time"`         // e.g. 1612345678901
}

LastModified struct for last modified timestamp

type LifecycleStateInfoPost added in v0.1.1

type LifecycleStateInfoPost struct {
	IsEditedByAuthor bool `json:"isEditedByAuthor"`
}

LifecycleStateInfoPost struct for LinkedIn post lifecycle state information

type Link struct {
	Type string `json:"type"` // application/json
	Rel  string `json:"rel"`  // prev, next
	Href string `json:"href"`
}

Link struct for pagination

type LogoV2 added in v0.1.1

type LogoV2 struct {
	Original string `json:"original"`
}

LogoV2 struct for logo

type Method

type Method string

Method - HTTP method for an API call.

const (
	GET    Method = "GET"
	POST   Method = "POST"
	PUT    Method = "PUT"
	DELETE Method = "DELETE"
)

HTTP API methods.

type NameLocalized added in v0.1.1

type NameLocalized struct {
	Localized       map[string]string `json:"localized"`
	PreferredLocale DefaultLocale     `json:"preferredLocale"`
}

NameLocalized struct for localized name

type Organization added in v0.1.1

type Organization struct {
	Paging   Paging                `json:"paging"`
	Elements []ElementOrganization `json:"elements"`
}

Organization struct for LinkedIn organizations

type OrganizationInfo added in v0.1.1

type OrganizationInfo struct {
	VanityName              string        `json:"vanityName"`
	LocalizedName           string        `json:"localizedName"`
	Created                 Created       `json:"created"`
	VersionTag              string        `json:"versionTag"`
	CoverPhotoV2            CoverPhotoV2  `json:"coverPhotoV2"`
	OrganizationType        string        `json:"organizationType"` // e.g. SELF_OWNED
	DefaultLocale           DefaultLocale `json:"defaultLocale"`
	LocalizedSpecialties    []string      `json:"localizedSpecialties"`
	Name                    NameLocalized `json:"name"`
	PrimaryOrganizationType string        `json:"primaryOrganizationType"` // e.g. NONE
	LastModified            LastModified  `json:"lastModified"`
	ID                      int64         `json:"id"` // ID of the organization
	LocalizedDescription    string        `json:"localizedDescription"`
	AutoCreated             bool          `json:"autoCreated"`
	LocalizedWebsite        string        `json:"localizedWebsite"`
	LogoV2                  LogoV2        `json:"logoV2"`
}

OrganizationInfo struct for LinkedIn organization information

func (*OrganizationInfo) GetOrganizationID added in v0.1.1

func (oi *OrganizationInfo) GetOrganizationID() int64

GetOrganizationID returns the organization ID from the details of the organization

type Paging added in v0.1.1

type Paging struct {
	Start int    `json:"start"`
	Count int    `json:"count"`
	Links []Link `json:"links"`
	Total int    `json:"total"`
}

Paging struct for pagination

func (*Paging) GetNext added in v0.1.1

func (p *Paging) GetNext() (bool, string)

GetNext returns the next page URL

func (*Paging) GetPrev added in v0.1.1

func (p *Paging) GetPrev() (bool, string)

GetPrev returns the previous page URL

type Params

type Params map[string]interface{}

Params to construct the request payload.

type Post added in v0.1.1

type Post struct {
	Paging   Paging        `json:"paging"`
	Elements []ElementPost `json:"elements"`
}

Post struct for LinkedIn posts

type ReshareContextPost added in v0.1.1

type ReshareContextPost struct {
	Parent string `json:"parent"` // e.g. urn:li:ugcPost:123456
	Root   string `json:"root"`   // e.g. urn:li:ugcPost:123456
}

ReshareContextPost struct for LinkedIn post reshare context

type RestLiMethod

type RestLiMethod string

RestLiMethod - LinkedIn Rest.Li method type

const (
	Get                RestLiMethod = "GET"
	BatchGet           RestLiMethod = "BATCH_GET"
	GetAll             RestLiMethod = "GET_ALL"
	Finder             RestLiMethod = "FINDER"
	BatchFinder        RestLiMethod = "BATCH_FINDER"
	Create             RestLiMethod = "CREATE"
	BatchCreate        RestLiMethod = "BATCH_CREATE"
	Update             RestLiMethod = "UPDATE"
	BatchUpdate        RestLiMethod = "BATCH_UPDATE"
	PartialUpdate      RestLiMethod = "PARTIAL_UPDATE"
	BatchPartialUpdate RestLiMethod = "BATCH_PARTIAL_UPDATE"
	Delete             RestLiMethod = "DELETE"
	BatchDelete        RestLiMethod = "BATCH_DELETE"
	Action             RestLiMethod = "ACTION"
)

LinkedIn Rest.Li methods

type Result

type Result map[string]interface{}

Result - response body from LinkedIn API call request.

type Session

type Session struct {
	HTTPClient HTTPClient // HTTP client to send requests
	BaseURL    string     // set to override API base URL

	LinkedInVersion string // e.g. 202404
	// contains filtered or unexported fields
}

Session holds a LinkedIn session with an access token. Session should be created by App.Session.

func (*Session) AccessToken

func (session *Session) AccessToken() string

AccessToken returns current access token.

func (*Session) App

func (session *Session) App() *App

App returns associated App.

func (*Session) Context

func (session *Session) Context() context.Context

Context returns the session's context. To change the context, use `Session#WithContext`.

The returned context is always non-nil; it defaults to the background context. For outgoing LinkedIn API requests, the context controls timeout/deadline and cancellation.

func (*Session) Get

func (session *Session) Get(uri string) (response *http.Response, data []byte, err error)

Get sends a GET request to LinkedIn API and returns the response.

func (*Session) Introspect

func (session *Session) Introspect(token string) (TokenData, error)

Introspect checks the Time to Live (TTL) and status (active/expired) for the given token.

See: https://learn.microsoft.com/en-us/linkedin/shared/authentication/token-introspection?toc=%2Flinkedin%2Fmarketing%2Ftoc.json&bc=%2Flinkedin%2Fbreadcrumb%2Ftoc.json&view=li-lms-2024-04&tabs=http

func (*Session) SetAccessToken

func (session *Session) SetAccessToken(token string)

SetAccessToken sets a new access token.

func (*Session) SetLinkedInVersion added in v0.1.1

func (session *Session) SetLinkedInVersion(version string)

SetLinkedInVersion overrides the default LinkedIn API version.

func (*Session) UseAuthorizationHeader

func (session *Session) UseAuthorizationHeader()

UseAuthorizationHeader passes `access_token` in HTTP Authorization header.

func (*Session) WithContext

func (session *Session) WithContext(ctx context.Context) *Session

WithContext returns a shallow copy of session with its context changed to ctx. The provided ctx must be non-nil.

type Token

type Token struct {
	AccessToken           string `json:"access_token"`
	ExpiresIn             int64  `json:"expires_in"`
	RefreshToken          string `json:"refresh_token"`
	RefreshTokenExpiresIn int64  `json:"refresh_token_expires_in"`
	Scope                 string `json:"scope"`
}

Token - access and refresh tokens.

See: https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?toc=%2Flinkedin%2Fmarketing%2Ftoc.json&bc=%2Flinkedin%2Fbreadcrumb%2Ftoc.json&view=li-lms-2024-04&tabs=HTTPS1#step-3-exchange-authorization-code-for-an-access-token

type TokenData

type TokenData struct {
	Active       bool   `json:"active"`
	ClientID     string `json:"client_id"`
	AuthorizedAt int64  `json:"authorized_at"`
	CreatedAt    int64  `json:"created_at"`
	Status       string `json:"status"`
	ExpiresAt    int64  `json:"expires_at"`
	Scope        string `json:"scope"`
	AuthType     string `json:"auth_type"`
}

TokenData - access and refresh token data after token inspection.

See: https://learn.microsoft.com/en-us/linkedin/shared/authentication/token-introspection?context=linkedin/context

Directories

Path Synopsis
_example
auth
Package main - LinkedIn OAuth authorization code flow example.
Package main - LinkedIn OAuth authorization code flow example.
me
Package main - LinkedIn HTTP GET example.
Package main - LinkedIn HTTP GET example.
organization
Get list of organizations managed by the authenticated user.
Get list of organizations managed by the authenticated user.
post
Fetch published posts from a LinkedIn page
Fetch published posts from a LinkedIn page

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL