Adding an image as an attachment to an Azure DevOps work item using the "Attachments - Create" API does not render when opened - azure-devops-rest-api

I've gone through several other SO pages and while it did help me with understanding how the upload of attachments to work item works, I still cannot find a way to view the said attachment after successfully uploading it via API, especially if its an image.
APIs I've used:
To create an attachment link: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-server-rest-5.0
Using the attachment URL retrieved from the previous API response, I use it in the Work Item Update API, below is a snippet:
api = f"https://dev.azure.com/{organization}/_apis/wit/workitems/{work_item_id}?api-version=6.0"
file_size = os.path.getsize(file_path)
payload = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": attachment_url,
"attributes": {
"comment": "Test",
"resourceSize": file_size
}
}
}
]
After this, the attachment is visible in the work item but when clicked on, it does not render the image. Instead a window opens and an infinite loading screen animation plays.
Its got to be the encoding of the image thats causing this however I cannot find any documentation.
Below is the full code for uploading attachments to an existing work item.
def upload_attachment(file_path, work_item_id):
# This part retrieves the Attachment URL
headers = {
"Accept": "application/json",
"Content-Size": str(os.path.getsize(file_path)),
"Content-Type": "application/octet-stream",
}
files = {'attachment': open(file_path, 'rb')}
filename = os.path.basename(file_path)
api = f"https://dev.azure.com/{organization}/{project}/_apis/wit/attachments?uploadType=Simple&fileName={filename}&api-version=1.0"
resp = requests.post(url=api, files=files, headers=headers, auth=("","*fmhcstt*4nwadqy3uk*go23fga"))
attachment_url = resp.json()['url']
# This part updates an existing work item, adding the attachment here.
api = f"https://dev.azure.com/{organization}/_apis/wit/workitems/{work_item_id}?api-version=6.0"
file_size = os.path.getsize(file_path)
payload = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": attachment_url,
"attributes": {
"comment": "Test",
"resourceSize": file_size
}
}
}
]
headers = {
'Accept':'application/json',
'dataType': 'application/json-patch+json',
'Content-type':'application/json-patch+json'
}
resp = requests.patch(url=api, headers=headers, json=payload, auth=("","*fmhcstt*4nwadqy3uk*go23fga"))

I found the issue to be with the POST request.
requests.post(url=api, files=files, headers=headers, auth=("","*fmhcstt*4nwadqy3uk*go23fga"))
Should have been:
requests.post(url=api, data=files, ...

Related

insert multiply records to a form, from JSON file using postman

How can I insert multiply records to a form using postman?
my data is in JSON file
and I use POST request:
"https://jrpostest.domjr.local/odata/Priority/tabula.ini/jrdf/SUPPLIERS"
getting the error below
You can use batch request in order to insert multiple records into a parent form with
one server call.
POST
https://jrpostest.domjr.local/odata/Priority/tabula.ini/jrdf/$batch
{
"requests": [
{
"method": "POST",
"url": "SUPPLIERS",
"body": {
"SUPNAME": "33445566",
"SUPDES": "33445566"
}
},
{
"method": "POST",
"url": "SUPPLIERS",
"body": {
"SUPNAME": "33445577",
"SUPDES": "33445577"
}
}
]
}
Please note that batch requests are available from Priority version 19.1.
In previous versions you will need to send two POST requests to the SUPPLIERS endpoint.

Jira API: Add Comment Using Edit Endpoint

Jira has a an /edit endpoint which can be used to add a comment. There is an example in their documentation that suggests this input body to accomplish this:
{
"update": {
"comment": [
{
"add": {
"body": "It is time to finish this task"
}
}
]
}
}
I create the exact same input in my Java code:
private String createEditBody() {
JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
ObjectNode payload = jsonNodeFactory.objectNode();
ObjectNode update = payload.putObject("update");
ArrayNode comments = update.putArray("comment");
ObjectNode add = comments.addObject();
ObjectNode commentBody = add.putObject("add");
commentBody.put("body", "this is a test");
return payload.toString();
}
but when I send this PUT request I get an error saying that the "Operation value must be of type Atlassian Document Format"!
Checking the ADF format it says that "version", "type" and "content" are required for this format. So although their documentation example doesn't seem to be ADF format, I'm trying to guess the format and change it. Here's what I accomplished after modifying my code:
{
"update": {
"comment": [
{
"add": {
"version": 1,
"type": "paragraph",
"content": [
{
"body": "this is a test"
}
]
}
}
]
}
}
the add operation seems to be an ADF but now I get 500 (internal server error). Can you help me find the issue?
Note that the above example from Atlassian documentation is for "Jira Server Platform" but the instance I'm working with is "Jira Cloud Platform" although I think the behaviour should be the same for this endpoint.
after tinkering with the input body, I was able to form the right request body! This will work:
{
"update": {
"comment": [
{
"add": {
"body": {
"version": 1,
"type": "doc",
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "this is a test"
}
]
}
]
}
}
}
]
}
}
The annoying things that I learned along the way:
Jira's documentation is WRONG!! Sending the request in their example will fail!!
after making a few changes, I was able to get 204 from the endpoint while still comment was not being posted! And I guessed that the format is not correct and kept digging! But don't know why Jira returns 204 when it fails!!!

TFS Attachement size 0KB via REST Call

Whenever i tried to attach attachment with TFS WorkItem via REST call, attachment size is 0KB.
First I upload an attachment in Attachment Store using below code.
https://{instance}/DefaultCollection/_apis/wit/attachments?api-version=1.0&filename="{fileName}"
I send data in bytes array through rest call. and after this i attach that attachment with workitem.
Attaching attachment is success but size of an attachment is zero KB
Is there is an issue with TFS or something i am doing wrong?
I am using C# language for programming and REST Sharp for accessing VSTS APIs
Dim restClient = New RestClient("Server URL")
restClient.Authenticator = New HttpBasicAuthenticator("UserId", "Password")
Dim request = New RestRequest("API_Name", Method.POST)
request.AlwaysMultipartFormData = False
request.AddParameter(String.Format("{0}; charset=utf-8", contentType), File.ReadAllBytes(filePath), ParameterType.RequestBody)
request.RequestFormat = DataFormat.Json
Dim response As IRestResponse = restClient.Execute(request)
Return response
I am sending file data in bytes.
Attaching Attachment with WorkItem.
Dim restClient = New RestClient(ACCESS_URL)
restClient.Authenticator = New HttpBasicAuthenticator(USER_NAME, PASSWORD)
Dim request = New
RestRequest("CollectionName}/_apis/wit/workitems/{WorkItem_ID}", Method.PATCH)
request.AddParameter("application/json-patch+json; charset=utf-8",
"post_Data", ParameterType.RequestBody)
request.RequestFormat = DataFormat.Json
Dim response As IRestResponse = restClient.Execute(request)
Return response
Post_Data is an json string which take this type of data
[{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": "AttachementURI",
}]
You missed "attributes" section in the Post_Data, try with below:
[{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": "AttachementURI",
"attributes": {
}
}]
I can reproduce this issue when keep the { file-contents } as empty.
So, make sure you have specified the { file-contents }.
To attach a file to a work item, upload the attachment to the
attachment store, then attach it to the work item. See Add an attachment for details.
Upload an attachment:
POST https://{instance}/DefaultCollection/_apis/wit/attachments?api-version={version}&filename=Spec.txt
Content-Type: application/octet-stream
{ file-contents }
Add an attachment for specific work item:
PATCH https://fabrikam-fiber-inc.visualstudio.com/DefaultCollection/_apis/wit/workitems/299?api-version=1.0
Content-Type: application/json-patch+json
[
{
"op": "test",
"path": "/rev",
"value": 3
},
{
"op": "add",
"path": "/fields/System.History",
"value": "Adding the necessary spec"
},
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": "https://fabrikam-fiber-inc.visualstudio.com/DefaultCollection/_apis/wit/attachments/098a279a-60b9-40a8-868b-b7fd00c0a439?fileName=Spec.txt",
"attributes": {
"comment": "Spec for the work"
}
}
}
]
See below C# sample to upload and add the attachment for a work item:
C# (UploadTextFile method)
C# (AddAttachment method)

How to retrieve contents of an itemAttachment via the Microsoft Graph API

I'm currently developing a solution which is retrieving e-mails via the Microsoft Graph API. In november 2015 Microsoft stated it is ready for production and I've read in another forum post that if you start now on developing using a Microsoft API, you should use the Graph API, since it is the future.
Everything is going well except for one thing and that is the following.
I must retrieve e-mails. Inside these e-mails there are of course attachments. These attachments come in some variaties. fileAttachment (images, documents etc.), referenceAttachments and itemAttachments (outlook-item). The issue here is with the itemAttachments. An itemAttachment can be anything from an appointment to another message. The problem here is that I'm not able to get and retrieve the contentBytes in some way which is working for fileAttachments. A related object to itemAttachment is outlookItem. There is also a page with a description made for this outlookItem, but the examples and the details are missing.
The user rights are set to Mail.Read and Mail.ReadWrite.
Links:
General overview: http://graph.microsoft.io/docs/overview/overview
Get outlookItem (empty?):
Example call and response I get. Please note the types of the attachments.
https://graph.microsoft.com/v1.0 /users/ /messages/ /attachments
{
"#odata.context": "link",
"value": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"id": "AAMkAGU2NmIwMTcxLTljYzUtNGRiMi1hZjczLTllNzhiZDRiNWZlZABGAAAAPAD_Lx_gimDGRqSr98J_O_e6BwDcWyYHlO7rS5_XpLHCx6NSAAIMC0V-AADcWyYHlO7rS5_XpLHCx6NSAAIMC6RgAAABEgAQAGhN_vm1RlBPt7V4N9a89UY=",
"lastModifiedDateTime": "2016-01-13T14:25:33Z",
"name": "image001.png",
"contentType": "image/png",
"size": 5077,
"isInline": true,
"contentId": "image001.png#01D14E16.A3A32480",
"contentLocation": null,
"contentBytes": "iVBORw0KGgoAAAANSUhEUgAAAKAAAACCCAIAAABOyVRHAAAAAXNSR0IArs4c6QAAEndJREFUeF7tXQ1QFFe2bkbU... (truncated)"
},
{
"#odata.type": "#microsoft.graph.fileAttachment",
"id": "AAMkAGU2NmIwMTcxLTljYzUtNGRiMi1hZjczLTllNzhiZDRiNWZlZABGAAAAPAD_Lx_gimDGRqSr98J_O_e6BwDcWyYHlO7rS5_XpLHCx6NSAAIMC0V-AADcWyYHlO7rS5_XpLHCx6NSAAIMC6RgAAABEgAQAFnSLgIC5wZOosmLtBWK8gE=",
"lastModifiedDateTime": "2016-01-13T14:25:34Z",
"name": "image002.png",
"contentType": "image/png",
"size": 3722,
"isInline": true,
"contentId": "image002.png#01D14E16.A3A32480",
"contentLocation": null,
"contentBytes": "iVBORw0KGgoAAAANSUhEUgAAAPoAAABSCAYAAAB9o8m+AAAAGXRFWHRTb... (truncated)"
},
{
"#odata.type": "#microsoft.graph.fileAttachment",
"id": "AAMkAGU2NmIwMTcxLTljYzUtNGRiMi1hZjczLTllNzhiZDRiNWZlZABGAAAAPAD_Lx_gimDGRqSr98J_O_e6BwDcWyYHlO7rS5_XpLHCx6NSAAIMC0V-AADcWyYHlO7rS5_XpLHCx6NSAAIMC6RgAAABEgAQANOuw7m8sW1Ot3MivYQ5OYU=",
"lastModifiedDateTime": "2016-01-13T14:25:24Z",
"name": "Knipsel.PNG",
"contentType": null,
"size": 7641,
"isInline": false,
"contentId": null,
"contentLocation": null,
"contentBytes": "iVBORw0KGgoAAAANSUhEUgAAAKAAAACCCAYAAADBq8MQAAA... (truncated)"
},
{
"#odata.type": "#microsoft.graph.itemAttachment",
"id": "AAMkAGU2NmIwMTcxLTljYzUtNGRiMi1hZjczLTllNzhiZDRiNWZlZABGAAAAPAD_Lx_gimDGRqSr98J_O_e6BwDcWyYHlO7rS5_XpLHCx6NSAAIMC0V-AADcWyYHlO7rS5_XpLHCx6NSAAIMC6RgAAABEgAQAPEUC740tjtAlNTe8NpopUI=",
"lastModifiedDateTime": "2016-01-14T15:55:07Z",
"name": "RE: Test met plaatje",
"contentType": null,
"size": 36972,
"isInline": false
}
]
}
I've tried to change the GET-statement by pasting the attachment id with or without the messages path and the expand feature (which is only supported one level deep), but I can't seem te find the solution.
Something I've found is this question, which is kind of the same, however it is for the office365 unified API. How to retrieve ItemAttachment contents from Office 365 REST API?.
So, the question: How can I retrieve the contents of an outlookItem via the Microsoft Graph API? And how do I know what to expect? Can anybody help me getting past this obstacle.
Use $expand option:
GET https://graph.microsoft.com/v1.0/me/messages('AAMkADA1M-zAAA=')/attachments('AAMkADA1M-CJKtzmnlcqVgqI=')/?$expand=microsoft.graph.itemattachment/item
Response:
HTTP/1.1 200 OK
Content-type: application/json
{
"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users('d1a2fae9-db66-4cc9-8133-2184c77af1b8')/messages('AAMkADA1M-zAAA%3D')/attachments/$entity",
"#odata.type":"#microsoft.graph.itemAttachment",
"id":"AAMkADA1MCJKtzmnlcqVgqI=",
"lastModifiedDateTime":"2017-07-21T00:20:34Z",
"name":"Reminder - please bring laptop",
"contentType":null,
"size":32005,
"isInline":false,
"item#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users('d1a2fae9-db66-4cc9-8133-2184c77af1b8')/messages('AAMkADA1M-zAAA%3D')/attachments('AAMkADA1M-CJKtzmnlcqVgqI%3D')/microsoft.graph.itemAttachment/item/$entity",
"item":{
"#odata.type":"#microsoft.graph.message",
"id":"",
"createdDateTime":"2017-07-21T00:20:41Z",
"lastModifiedDateTime":"2017-07-21T00:20:34Z",
"receivedDateTime":"2017-07-21T00:19:55Z",
"sentDateTime":"2017-07-21T00:19:52Z",
"hasAttachments":false,
"internetMessageId":"<BY2PR15MB05189A084C01F466709E414F9CA40#BY2PR15MB0518.namprd15.prod.outlook.com>",
"subject":"Reminder - please bring laptop",
"importance":"normal",
"conversationId":"AAQkADA1MzMyOGI4LTlkZDctNDkzYy05M2RiLTdiN2E1NDE3MTRkOQAQAMG_NSCMBqdKrLa2EmR-lO0=",
"isDeliveryReceiptRequested":false,
"isReadReceiptRequested":false,
"isRead":false,
"isDraft":false,
"webLink":"https://outlook.office365.com/owa/?ItemID=AAMkADA1M3MTRkOQAAAA%3D%3D&exvsurl=1&viewmodel=ReadMessageItem",
"body":{
"contentType":"html",
"content":"<html><head>\r\n</head>\r\n<body>\r\n</body>\r\n</html>"
},
"sender":{
"emailAddress":{
"name":"Adele Vance",
"address":"AdeleV#contoso.onmicrosoft.com"
}
},
"from":{
"emailAddress":{
"name":"Adele Vance",
"address":"AdeleV#contoso.onmicrosoft.com"
}
},
"toRecipients":[
{
"emailAddress":{
"name":"Alex Wilbur",
"address":"AlexW#contoso.onmicrosoft.com"
}
}
],
"ccRecipients":[
{
"emailAddress":{
"name":"Adele Vance",
"address":"AdeleV#contoso.onmicrosoft.com"
}
}
]
}
}
Source: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/attachment_get#request-2
The official documentation: https://graph.microsoft.io/en-us/docs/api-reference/beta/api/attachment_get.htm . Use valid Bearer authentication access code, and check for appropriate Graph API permissions on the Azure management portal. Attachment is based64 encoded string, coming in the contentBytes field. Correct Uri for loading list of a message attachments is: https://graph.microsoft.com/beta/me/messages/[ message Id ]/attachments. Sample code to call attachments endpoint is below:
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get,
"https://graph.microsoft.com/beta/me/messages/..id../attachments"))
{
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", "...valid access token...");
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (response.StatusCode == HttpStatusCode.OK)
{
result = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(result);
}
}
}
}
Get attachment using MS Graph API for Java:
First build the graph client. Sample code
ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId(yourClientId).clientSecret(yourClientSecret)
.tenantId(yourTenantId).build();
TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(clientSecretCredential);
GraphServiceClient<Request> gClient = GraphServiceClient.builder().authenticationProvider(tokenCredAuthProvider)
.buildClient();
Either get all the attachments for a message-
FileAttachment fa = (FileAttachment) graphClient.users(id).messages(messageId).attachments().buildRequest().get();
Or get a particular attachment by passing the attachment id:
FileAttachment fa = (FileAttachment) graphClient.users(id).messages(messageId).attachments(attachmentId).buildRequest().get();
//Copy file attachment into a File from byte stream using FileUtils.
FileUtils.writeByteArrayToFile(new File(yourFileLocation), fa.contentBytes);
You can also similarly either get all users, messages or attachments or pass particular id to get a unique result for these entities.

Getting title and description of embedded YouTube video

On a site I'm developing I embed videos from YouTube and want to get the video title and its description.
How do I get that information?
You can do it with oembed.
Example:
http://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3DM3r2XDceM6A&format=json
Youtube API V2.0 has been deprecated. It shows some wrong value for title "youtube.com/devicesupport" . pLease switch on to API V3.0
YOu can refer the following PHP code and modify yours in js or jquery as per your needs..
function youtube_title($id) {
$id = 'YOUTUBE_ID';
// returns a single line of JSON that contains the video title. Not a giant request.
$videoTitle = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=".$id."&key=YOUR_API_KEY&fields=items(id,snippet(title),statistics)&part=snippet,statistics");
// despite # suppress, it will be false if it fails
if ($videoTitle) {
$json = json_decode($videoTitle, true);
return $json['items'][0]['snippet']['title'];
} else {
return false;
}
}
update:
Jquery code to get the title-
$.getJSON('https://www.googleapis.com/youtube/v3/videos?id={VIDEOID}&key={YOUR API KEY}&part=snippet&callback=?',function(data){
if (typeof(data.items[0]) != "undefined") {
console.log('video exists ' + data.items[0].snippet.title);
} else {
console.log('video not exists');
}
});
To get the DESCRIPTION element, you need to access the gdata version of the video's info, and you can return json using alt=json on the path. In this case, oHg5SJYRHA0 is the video ID, found at the end of the url of the video you're working with on YouTube, e.g.
www.youtube.com/watch?v=oHg5SJYRHA0
http://gdata.youtube.com/feeds/api/videos/oHg5SJYRHA0?v=2&alt=json&prettyprint=true
(the prettyprint is formatting to make that easy to read, you don't need it for what you're doing)
You can grab the JSON, add it into a variable and access it using jQuery:
var youTubeURL = 'http://gdata.youtube.com/feeds/api/videos/oHg5SJYRHA0?v=2&alt=json';
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': youTubeURL,
'dataType': "json",
'success': function(data) {
json = data;
}
});
return json;
})();
Then access it using object notation:
alert("Title: " + json.entry.title.$t +"\nDescription:\n " + json.entry.media$group.media$description.$t + "\n");
gdata is no longer available
you can use the following instead
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=(Video_ID)&key=(API_Key)
I read this topic a bit in delay.
I did something like this using jSON and YT API's
$json = json_decode( file_get_contents("http://gdata.youtube.com/feeds/api/videos/".$rs['vid']."?v=2&prettyprint=true&alt=jsonc") );
Note: $rs['vid'] is the video ID dinamically retrived from my DB.
Once you put the contents in the handle $json you can retrive like this:
$json->data->description;
$json->data->title;
use var_dump( $json ) to view all values you can access.
I'd start by taking a look at Youtube Data API to get what you want: http://code.google.com/apis/youtube/getting_started.html#data_api
GData is deprecated, but one can still get the video description by calling this endpoint:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=[video_id]&key=[api_key]
It will return a response of the form:
{
"kind": "youtube#videoListResponse",
"etag": "\"...\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"...\"",
"id": "...",
"snippet": {
"publishedAt": "...",
"channelId": "...",
"title": "...",
"description": "...",
"thumbnails": { ... },
"channelTitle": "...",
"tags": [ ... ],
"categoryId": "...",
"liveBroadcastContent": "...",
"localized": {
"title": "...",
"description": "..."
},
"defaultAudioLanguage": "..."
}
}
]
}
The description can be found at items.localized.description.

Resources