Let us face it! REST is the order of the day. And Atlassian just underlined that statement with the release of JIRA5. With JIRA5, a lot of the operations can be done using the REST API and here is the full list of operations supported. There are so many ways to invoke the rest APIs. The Atlassian developer documentation is a good start. It gives you a good explanation on the input parameters needed for the various operations, if not fully clear from the API documentation. But if you are yet unsure on how to invoke these REST operations from a Java client, read on... Before boring you further, I must say that the best Java client for JIRA REST APIs is JRJC - The JIRA Rest Java Client supported by Atlassian. But at least for now, it doesn't support all the Issue CRUD methods. I must add that it won't be long before they are added (or is available when you re reading it!). Still, what if you want to create another client? Without the dependency on something like JRJC? Let us look at a rather simple option - Using Jersey to write a REST Client. I have mentioned about JRJC in my book but the following part is probably missing from the book. Considering the JIRA5 REST capabilities, it is never too late to write something about it, is it? As mentioned before, I am just going to look at Jersey and see how we can write a simple client. Let us start with creating a simple maven project. Following is the dependency that needs to be added for using the jersey client libraries. <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.8</version> </dependency> Change the version as appropriate! Consider a simple scenario. We need to get a list of all projects in a JIRA instance. As per the API docs, the REST url is /rest/api/2/project and it is a GET operation. Following are the steps:
As you can see, we have set the basic authentication parameters in the header which includes the authentication String we created in Step 2. You can add even custom values in the header as long as the server can use it but in our case that is not required. The media type we used is application/json as that is the one supported by JIRA REST methods. We are also using the get method here and accepts the response into the ClientResponse class. That's it! We have sent the request and got the response. It is now only a matter of making sure the response is what is expected. The easiest thing to do is to check the status code in the response. For example, a response code in the 200 range is normally successful where as 401, for example, indicates invalid authentication error! A good list of status codes can be found here. You can get the status code and check it like this: int statusCode = response.getStatus(); if (statusCode == 401) { throw new AuthenticationException("Invalid Username or Password"); } And what is the status code is fine? If you are expecting a response, like in our case - list of projects, we can get the result as shown: String response = response.getEntity(String.class); Here the response will be in json format since that is what is given back by JIRA. Remember, the media type we set was application/json! A sample output is here: [ { "self": "http://localhost:8080/rest/api/2/project/DEMO", "id": "10000", "key": "DEMO", "name": "DEMO", "avatarUrls": { "16x16": "http://localhost:8080/secure/projectavatar?size=small&pid=10000&avatarId=10011", "48x48": "http://localhost:8080/secure/projectavatar?pid=10000&avatarId=10011" } }, { "self": "http://localhost:8080/rest/api/2/project/TEST", "id": "10001", "key": "TEST", "name": "TEST", "avatarUrls": { "16x16": "http://localhost:8080/secure/projectavatar?size=small&pid=10001&avatarId=10011", "48x48": "http://localhost:8080/secure/projectavatar?pid=10001&avatarId=10011" } } ] As you can see, the response here is a JSON array and you can now extract the details from here as you wish! Here is small example of extracting the key and name. We will use JSON in java for this. The dependency to be added is: <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> You can simply extract the key and name as follows: JSONArray projectArray = new JSONArray(jsonResponse); for (int i = 0; i < projectArray.length(); i++) { JSONObject proj = projectArray.getJSONObject(i); System.out.println("Key:"+proj.getString("key")+", Name:"+proj.getString("name")); } So, that was a simple GET example. How about creating/updating/deleting an issue? I have taken these examples because they use POST/PUT/DELETE operations. Creating an issue As per the docs, we need to POST the fields required to create the issue to the REST resource. The url is http://localhost:8080/rest/api/2/issue and the simple json input with just summary, project and issuetype details will be something like this: {"fields":{"project":{"key":"DEMO"},"summary":"REST Test","issuetype":{"name":"Bug"}}} Everything else remains the same expect that we will be using post method with the above data. private static String invokePostMethod(String auth, String url, String data) throws AuthenticationException, ClientHandlerException { Client client = Client.create(); WebResource webResource = client.resource(url); ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json") .accept("application/json").post(ClientResponse.class, data); int statusCode = response.getStatus(); if (statusCode == 401) { throw new AuthenticationException("Invalid Username or Password"); } return response.getEntity(String.class); } Updating an issue The url will have the issue key we need to edit: http://localhost:8080/rest/api/2/issue/DEMO-13. A simple example of json data to change the assignee will be: {"fields":{"assignee":{"name":"test"}}} Everything else remains same except that we use the PUT method: private static void invokePutMethod(String auth, String url, String data) throws AuthenticationException, ClientHandlerException { Client client = Client.create(); WebResource webResource = client.resource(url); ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json") .accept("application/json").put(ClientResponse.class, data); int statusCode = response.getStatus(); if (statusCode == 401) { throw new AuthenticationException("Invalid Username or Password"); } } Note that we are not returning any response here since the REST method doesn't return anything. The status code of 204 indicates 'No Content'. Deleting an issue As you would expect, this doesn't need any additional data as the url has the issue key in it: http://localhost:8080/rest/api/2/issue/DEMO-13. The operation is DELETE as opposed to PUT. private static void invokeDeleteMethod(String auth, String url) throws AuthenticationException, ClientHandlerException { Client client = Client.create(); WebResource webResource = client.resource(url); ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json") .accept("application/json").delete(ClientResponse.class); int statusCode = response.getStatus(); if (statusCode == 401) { throw new AuthenticationException("Invalid Username or Password"); } } Well, that wraps up the basics. Everything else is just an extension of this. https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Tutorials has a whole lot of examples with data for each operation. Also attached to this post is the Java project we used for this post. Don't forget to have a look at the JIRA Development Cookbook.
64 Comments
parthi
5/9/2012 10:42:02 pm
Nice 1 Jobin
Reply
J-Tricks
5/10/2012 01:11:22 am
Thanks Parthi. Glad you liked it :)
Reply
Fcornejo
6/25/2012 09:48:04 pm
Great job, it helped me a lot. Thanks!
Reply
Daniel
7/11/2012 02:22:51 pm
How would you go about attaching a file to an issue using jersey?
Reply
frank
7/23/2012 11:46:17 pm
Very nice examples, thanks a lot!
Reply
mike
8/3/2012 05:58:20 am
Thanks for the nice article. I am able to use rest api to get project information however stuck while trying to update an issue :(
Reply
J-Tricks
8/6/2012 09:52:16 am
Do you have "Assign Issue" permission for the issue? Are you able to do this operation from UI when logged in as the user you are trying from REST?
Reply
mike
8/6/2012 11:10:34 am
yea.. everything is good but now I know the reason.. many of the put/post methods are not supported before jira 5.0.x and I have jira old version.. so now I am using Soap client..
Reply
Chandramohan M
10/3/2012 08:08:11 am
Hi,
Reply
daeyong.park
10/29/2012 07:45:56 pm
Cool!!
Reply
sridhar
11/2/2012 06:14:45 am
I working on Rest api to get the issue details based on jira cook book and i am getting this error when trying to access jira from a standalone java application.
Reply
J-Tricks
11/2/2012 06:23:11 am
How is your json object constructed? Maybe you can post the code here?
Reply
Kannan
9/19/2015 02:11:14 am
import java.net.URI;
Sivanandam
2/1/2013 01:09:38 am
Hi,
Reply
J-Tricks
2/4/2013 11:11:25 am
What version of Jersey client is it?
Reply
Mizan
2/3/2013 08:21:54 pm
Hi JTricks ,
Reply
J-Tricks
2/4/2013 11:12:40 am
Sorry, I didn't understand. You can get any custom fields value via REST. What is different here?
Reply
Mizan
2/4/2013 05:17:28 pm
I have Vertigo SLA plugin installed , they provide some REST api ( https://confluence.valiantys.com/display/VSLA/REST+Access+Guide#RESTAccessGuide-Authorizations ) using this I can get Remaining value of the SLA customfield .
J-Tricks
2/5/2013 02:13:06 pm
You should probably create a Scripted field. Script runner plugin provides one.
Mizan
2/5/2013 04:15:54 pm
Thank you J-Tricks , I will try this . 6/16/2013 09:17:06 pm
I admire your thoughts and your way of expressing and putting it in front of readers "Java client" is really something that I have seen after a long time. We need more writers like you. This is perfect blog for anyone who is looking for topics like this. It has got it all, information, benefits and overview.
Reply
Suresh M
6/23/2013 11:41:18 pm
It was too cool. and helped me really. thanks
Reply
mizan
7/8/2013 12:31:34 am
Hi JTricks ,
Reply
J-Tricks
7/8/2013 01:34:58 am
Haven't tried it but I don't see an issue with that!
Reply
Joey
7/8/2013 08:49:27 am
J-Tricks,
Reply
J-Tricks
7/8/2013 09:38:58 am
This comes when you are connecting to an HTTPS connection. Make sure you import the public certificate of you JIRA instance to the keystore of the application which is using this code.
Reply
8/8/2013 01:32:02 am
Oh my God I was unaware of the facts you mentioned in your article "Java developer". It is so helpful that I am sure everyone will praise you for sharing this information. Wonderful work. This is something I was searching for many days. My thirst has been quenched now after reading your article. I am highly thankful to you for writing this article.
Reply
Lukas
10/2/2013 02:32:34 am
Hello there,
Reply
J-Tricks
10/2/2013 03:11:27 am
Use the documentation for 4.3.2 :)
Reply
Lukas
10/2/2013 05:24:35 am
Jesus Christ... i am so bad ^^
alekhya
2/12/2014 05:24:31 pm
Hi,
Reply
J-Tricks
2/13/2014 02:12:20 am
Makes ure you are using the right version and also the correct classes (check the import statements) ;)
Reply
alekhya
3/3/2014 07:21:26 pm
i have added all th eimports still the same error
alekhya
3/3/2014 07:28:20 pm
the same error with the source code also could not parse the accept() method
cseppd
3/2/2014 05:34:18 pm
My code:
Reply
J-Tricks
3/6/2014 03:40:23 pm
Sorry, you are missing the error!
Reply
cseppd
3/11/2014 12:30:09 am
My code: Client client = Client.create();
Reply
J-Tricks
3/11/2014 01:39:17 am
class file for java.net.URI not found.
Reply
cseppd
3/13/2014 02:45:21 am
In 3rd line:ClientResponse response = (ClientResponse)webResource.accept(new MediaType[]{MediaType.APPLICATION_JSON_TYPE}).get(ClientResponse.class); Get error: No suitable method found for accept(MediaType).Plz hlp..
s3
3/17/2014 10:35:46 am
Hi, I downloaded the code provided above and when I try and do an atlas-run I get the error message:
Reply
Sharath
10/28/2014 05:22:49 am
Just the thing i was looking for...thanks a lot!
Reply
Melek
1/15/2015 10:43:03 pm
Nice tutorials!! Thanks a lot it's simple and clear to understand :)
Reply
pritam
2/16/2015 04:25:26 am
I want to import issues from an excel file to jira website.The file must be passed from an interface which is built using eclipse.The contents in the excel file must be used to create and update issues.Could you please guide me how I can achieve this.
Reply
Ameya
4/6/2015 08:23:44 pm
Hi
Reply
J-Tricks
4/7/2015 01:32:54 am
Well, the basic steps are in this tutorial ;) Where are you stuck?
Reply
Ameya
4/8/2015 10:10:11 pm
Thanx. Using you tutorial it worked
Ameya
4/9/2015 10:24:05 pm
Till yesterday i had atlassian link which i used for jira rest api.
J-Tricks
4/10/2015 01:56:07 am
Code should be the same, except the URL, username/password changes. Assuming you already have JIRA set up locally.
Ameya
4/10/2015 02:07:09 am
I didnt had any setup yet.
J-Tricks
4/10/2015 02:41:07 am
You need to install JIRA locally. See https://confluence.atlassian.com/display/JIRA/JIRA+Installation+and+Upgrade+Guide
Thanks alot for the post, but i want to know why is the udpate method returning any data. If try to get the data following is the exception i receive but the issue is updated
Reply
Neha Agrawal
10/9/2015 02:57:28 am
Hi.. Is anyone know how to create jira webservices or wsdl file for connection with JIRA, creating the issue and query the issue ?
Reply
J-Tricks
10/9/2015 07:30:15 am
SOAP API is removed in JIRA 7/ we strongly recommend you to try REST.
Reply
Kannan
2/25/2016 11:44:10 am
Hi,
Reply
testreddy
10/25/2016 01:24:42 am
I am getting 400 BAD Request URL, when trying to create a new issue using JIRA REST API.
Reply
J-Tricks
10/26/2016 10:10:11 pm
400 is a valid response code. You will get it when the input is invalid (e.g. missing required fields, invalid field values, and so forth). Check the response text to find out the error!
Reply
Raj Rathore
12/28/2016 06:37:06 am
can anyone suggest how to add attachments to new issues from the issues obtained from jql.
Reply
Chris
3/21/2017 10:46:54 am
Wow.
Reply
Rashmi
8/6/2017 01:03:24 pm
Hi , I am working on JIRA Rest API with OAUTH. Please let me know if anyone has the working code on the same ?
Reply
Mopendra
7/30/2018 03:07:56 am
Hi,
Reply
Ismael Garnica
5/29/2021 07:47:38 am
Thank you so much! Helped me a lot.
Reply
Your comment will be posted after it is approved.
Leave a Reply. |
AuthorJobin Kuruvilla - Works in Adaptavist as Head of DevOps Professional Services. Categories
All
Archives
October 2016
|