Writing to LinkedIn APIs

When writing data to the LinkedIn API, you need to use additional HTTP methods above and beyond GET, such as POST, PUT and DELETE. Different operations require different HTTP methods depending on the intended action.

First, we will focus on creating new content using POST. Post requests include a content body defining what you want the new entity to look like, using JSON or XML. When you successfully write to an endpoint the response header will contain a 201, indicating the resource was created.

We can not emphasize strongly enough that you should always use a library to create your XML or JSON rather than trying to concatenate a string by hand or similar method of manually generating markup. There are many excellent libraries for reading and writing JSON and XML available for all modern programming languages. Use them, trust us, it will make your life easier when, not if, something breaks!

Here's a list of popular resources that you can write to:

Name Description Endpoint
Network update Sending updates to your network http://api.linkedin.com/v1/people/~/person-activities
Shares Sharing information with your network http://api.linkedin.com/v1/people/~/shares
Invitations Invite people to the users network http://api.linkedin.com/v1/people/~/mailbox
Company follow Start following a company http://api.linkedin.com/v1/people/~/following/companies
Join a Group Join a group http://api.linkedin.com/v1/people/~/group-memberships
Group post comment Posting a comment to a post in a group http://api.linkedin.com/v1/posts/{post-id}/comments

Since each programming language and library handles POST requests differently, the best way to demonstrate writing to the LinkedIn APIs is with code.

Example: Writing to the LinkedIn APIs

Before trying to execute the code below, it's assumed you have an API key/secret, have obtained an OAuth access token, and have successfully retrieved data from the LinkedIn API.

Here is an example that writes to the authenticated shares with an XML payload. We are going to write the following XML using a XML generation library to prevent issues with encodings and proper escaping.

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version='1.0' encoding='UTF-8'?>
<share>
   <comment>Posting from the API using XML</comment>
   <content>
      <title>A title for your share</title>                                                     
      <submitted-url>http://developer.linkedin.com</submitted-url>      
      <submitted-image-url>http://lnkd.in/Vjc5ec</submitted-image-url>  
   </content>
   <visibility>
      <code>anyone</code>
   </visibility>
</share>

Whenever you provide post data, you need to identify how it's formatted using the Content-Type HTTP header. In the case of XML, it's text/xml:

url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addHeader("Content-Type", "text/xml");

// Make an XML document using dom4j
Document doc = DocumentHelper.createDocument();
Element share = doc.addElement("share");
share.addElement("comment").addText("Posting from the API using XML");
Element content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
content.addElement("submitted-image-url").addText("http://lnkd.in/Vjc5ec");
share.addElement("visibility").addElement("code").addText("anyone");

request.addPayload(doc.asXML());

service.signRequest(accessToken, request);
response = request.send();

// there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
<?php

// here we create some XML which is used in the next two API calls
// XMLWriter2 is a wrapper around XMLWriter to allow chaining
// See the code download for the source to it
$xmlwriter = new XMLWriter2();
$xmlwriter->openMemory();
$xmlwriter->startDocument('1.0', 'UTF-8')->startElement("share");
	$xmlwriter->addElement("comment", $comment);
	$xmlwriter->startElement("content");
		$xmlwriter->addElement("title", $title);
		$xmlwriter->addElement("submitted-url", $url);
		$xmlwriter->addElement("submitted-image-url", $image);
	$xmlwriter->endElement();
	$xmlwriter->startElement("visibility")->addElement("code", $visibility)->endElement();
$xmlwriter->endElement()->endDocument();
$body_xml = $xmlwriter->outputMemory(TRUE);


print_line("\n********Write to the share - using XML********");
$api_url = "http://api.linkedin.com/v1/people/~/shares";
$oauth->fetch($api_url, $body_xml, OAUTH_HTTP_METHOD_POST, array("Content-Type" => "text/xml"));
print_response($oauth);
print "\n********Write to the share - using XML********"
	share_element = ET.Element("share")
	comment = ET.SubElement(share_element,"comment")
	comment.text = comment_text
		
	content_element = ET.SubElement(share_element,"content")
		
	title = ET.SubElement(content_element,"title")
	title.text = title_text
	submitted_url = ET.SubElement(content_element,"submitted-url")
	submitted_url.text = url
	submitted_image_url = ET.SubElement(content_element,"submitted-image-url")
	submitted_image_url.text = image
		
	visibility_element = ET.SubElement(share_element,"visibility")
	code_element = ET.SubElement(visibility_element,"code")
	code_element.text = visibility
		
	tree = ET.ElementTree(share_element)
	tree.write(xml_file,encoding="utf-8",xml_declaration=True)
	filehandle = open(xml_file)	
	xml_content = filehandle.read()
	api_url = "http://api.linkedin.com/v1/people/~/shares";
	headers = {"Content-Type":"text/xml"};
	response = make_request(client,api_url,headers,"Failed to post share","POST",xml_content)

Now we do a share and this time repost to a linked Twitter account. We will use a library to generate the JSON to avoid issues with encoding and escaping.

1
2
3
4
5
6
7
8
9
10
11
{ 
        "comment": "Posting from the API using JSON", 
        "content": { 
                "title": "A title for your share", 
                "submitted-url": "http://www.linkedin.com", 
                "submitted-image-url": "http://lnkd.in/Vjc5ec" 
        }, 
        "visibility": { 
                "code": "anyone" 
        } 
}

When using JSON, we need to set two HTTP headers:

url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);

// set the headers to the server knows what we are sending
request.addHeader("Content-Type", "application/json");
request.addHeader("x-li-format", "json");

// make the json payload using json-simple
HashMap jsonMap = new HashMap();
jsonMap.put("comment", "Posting from the API using JSON");

JSONObject contentObject = new JSONObject();
contentObject.put("title", "A title for your share");
contentObject.put("submitted-url","http://www.linkedin.com");
contentObject.put("submitted-image-url", "http://lnkd.in/Vjc5ec");

jsonMap.put("content", contentObject);

JSONObject visibilityObject = new JSONObject();
visibilityObject.put("code", "anyone");

jsonMap.put("visibility", visibilityObject);

request.addPayload(JSONValue.toJSONString(jsonMap));

service.signRequest(accessToken, request);
response = request.send();

// again no body - just headers
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
<?php

// here we build the JSON which is used to submit a share via JSON rather than XML
$body = new stdClass();
$body->comment = $comment;
$body->content = new stdClass();
$body->content->title = $title;
$body->content->{'submitted-url'} = $url;
$body->content->{'submitted-image-url'} = $image;
$body->visibility = new stdClass();
$body->visibility->code = $visibility;
$body_json = json_encode($body);

print_line("\n********Write to the share - using JSON********");
$api_url = "http://api.linkedin.com/v1/people/~/shares";
$oauth->fetch($api_url, $body_json, OAUTH_HTTP_METHOD_POST, array(
	"Content-Type" => "application/json",
	"x-li-format" => "json"
));
print_response($oauth);
print "\n********Write to the share - using JSON********"
	share_object = {
		"comment":comment_text,
		"content": {
			"title":title_text,
			"submitted_url":url,
			"submitted_image_url":image
		},
		"visibility": {
			"code":visibility
		}
	}
	
	json_content = simplejson.dumps(share_object)
	api_url = "http://api.linkedin.com/v1/people/~/shares";
	headers = {"Content-Type":"application/json"};
	response = make_request(client,api_url,headers,"Failed to post share","POST",json_content)