lu_lu
lu_lu

Reputation: 173

How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.

This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:

curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool

This is the React state hook for setting the data to the fetched data:

    const [jiraTicket, setJiraTicket] = useState([]);

This is the fetch function for the API request (${} will be filled with user input):

    function getJiraTicket() {
    axios.get(`${username}:${apiToken}@Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
        .then((res) => {
            const data = res.data;
            setJiraTicket(data);
        })
}

The button inside the react component return should invoke the fetch function:

return(
   <Container>
      <Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
   </Container>
);

This is the error I'm currently getting, because the authorization is not working the way I did it (I replaced the provided username, API token etc. for this example):

GET http://localhost:3000/username:apitoken@https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)

Edit:

My current approach:

    function getJiraTicket() {
    axios.get(`${userName}:${apiToken}@https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
        auth: {
            username: userName,
            password: apiToken,
        },
        withCredentials: true
    })
        .then((res) => {
            const data = res.data;
            console.log(data);
            setJiraTicket(data);
        })
        .catch(err => {
            // This error means: The request was made and the server responded with a status code
            if(err.res) {
                console.log(err.res.data);
                console.log(err.res.status);
                console.log(err.res.headers);
                console.log("request was made and server responded with status");
            // The request was made but no response was received
            } else if (err.request) {
                console.log(err.request);
                console.log("request was made, but no response was received");
            // Something happened in setting up the request that triggered an error
            } else {
                console.log("Error", err.message);
                console.log("request is note set up correctly");
            }
            console.log(err.config);
        })

Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"

Endpoint that works well in Postman (Basic auth is provided in Postman): https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid

Upvotes: 0

Views: 2707

Answers (2)

lu_lu
lu_lu

Reputation: 173

Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:

https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent

Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues

Upvotes: 0

Jamie_D
Jamie_D

Reputation: 999

Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:

let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
    baseURL: axiosUrl,
    method: 'get',
    headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin", "*"
    },
    //timeout: 2000,
    auth: {
        username: userName,
        password: apiToken,
    }
})
    .then((res) => {
        setJiraTicket(res.data);
    })
     .catch(function (error) {
         console.log(error);
     });

Upvotes: -1

Related Questions