DEV Community

Cover image for Improvements of Jira REST API Client
alexdodonov
alexdodonov

Posted on • Edited on

3 2

Improvements of Jira REST API Client

Hi all!

In the previous article I have shown how PHP client classes for varios REST APIs may be created.

Now I'am going to show how to submit data for creating entities.

First of all we need to improve request submitting method:

if (self::isHeaderExists($headers, 'Content-type: application/json')) {
    // converting data in JSON
    $formData = json_encode($data);
} else {
    $formData = [];
    foreach ($data as $key => $value) {
        $formData[] = $key . '=' . urlencode($value);
    }
    $formData = implode('&', $formData);
}

$curlConfig[CURLOPT_POSTFIELDS] = $formData;
Enter fullscreen mode Exit fullscreen mode

Then remove default headers wich were added automatically:

protected function getCommonHeaders(): array
{
    $result = $this->headers;

    if ($this->idempotencyKey !== '') {
        $result[] = 'Idempotency-Key: ' . $this->idempotencyKey;
    }

    // this default header must be removed because
    // Jira API returns error and Atlassian is not going
    // to fix it
    $result[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';

    return $result;
}
Enter fullscreen mode Exit fullscreen mode

New let's update our classes for calling API methods. First of all I have refactored methods for operations with connection:

trait ConnectionMethods
{

    /**
     * Connection to Jira
     *
     * @var Connection
     */
    private $connection = null;

    /**
     * Method returns connection to Jira
     *
     * @return Connection connection to Jira
     */
    protected function getConnection(): Connection
    {
        return $this->connection;
    }

    /**
     * Method returns connection to Jira
     *
     * @param Connection $connection
     *            connection to Jira
     */
    protected function setConnection(Connection $connection): void
    {
        $this->connection = $connection;
    }
}
Enter fullscreen mode Exit fullscreen mode

And now we create class for creating Jira issue:

class Issue
{

    use ConnectionMethods;

    /**
     * Issue data
     *
     * @var object
     */
    private $issue = null;

    /**
     * Constructor
     *
     * @param Connection $connection
     *            connection to Jira
     * @param object $issue
     *            data
     */
    public function __construct(Connection $connection)
    {
        $this->setConnection($connection);

        $this->issue = new \stdClass();
    }

    /**
     * Setting id
     *
     * @param int $id
     */
    public function setId(int $id): void
    {
        $this->issue->id = $id;
    }

    /**
     * Getting id
     *
     * @return int
     */
    public function getId(): int
    {
        if (! isset($this->issue->id)) {
            throw (new \Exception('Field "id"  was not found for the issue'));
        }

        return $this->issue->id;
    }

    /**
     * Setting summary
     *
     * @param string $summary
     *            summary
     */
    public function setSummary(string $summary): void
    {
        $this->issue->summary = $summary;
    }

    /**
     * Getting summary
     *
     * @return string summary
     */
    public function getSummary(): string
    {
        if (! isset($this->issue->summary)) {
            throw (new \Exception('Field "summary"  was not found for the issue'));
        }

        return $this->issue->summary;
    }

    /**
     * Setting description
     *
     * @param string $description
     *            description
     */
    public function setDescription(string $description): void
    {
        // since Jira REST API v3 setting description data
        // have become quite tricky )
        if (! isset($this->issue->description)) {
            $this->issue->description = new \stdClass();
            $this->issue->description->type = 'doc';
            $this->issue->description->version = 1;
        }

        $content = new \stdClass();
        $content->text = $description;
        $content->type = 'text';

        $paragraph = new \stdClass();
        $paragraph->type = 'paragraph';
        $paragraph->content = [];
        $paragraph->content[] = $content;

        $this->issue->description->content = [];
        $this->issue->description->content[] = $paragraph;
    }

    /**
     * Getting description
     *
     * @return object description
     */
    public function getDescription(): object
    {
        if (! isset($this->issue->description)) {
            throw (new \Exception('Field "description"  was not found for the issue'));
        }

        return $this->issue->description;
    }

    /**
     * Setting project key
     *
     * @param string $projectKey
     *            project key
     */
    public function setProjectKey(string $projectKey): void
    {
        if (! isset($this->issue->project)) {
            $this->issue->project = new \stdClass();
        }

        $this->issue->project->key = $projectKey;
    }

    /**
     * Getting project key
     *
     * @return string project key
     */
    public function getProjectKey(): string
    {
        if (! isset($this->issue->project) || ! isset($this->issue->project->key)) {
            throw (new \Exception('Field "project->key" was not found for the issue'));
        }

        return $this->issue->project->key;
    }

    /**
     * Getting project
     *
     * @return object project
     */
    public function getProject(): object
    {
        if (! isset($this->issue->project)) {
            throw (new \Exception('Field "project" was not found for the issue'));
        }

        return $this->issue->project;
    }

    /**
     * Setting issue type name
     *
     * @param string $issueTypeName
     *            issue type name
     */
    public function setIssueTypeName(string $issueTypeName): void
    {
        if (! isset($this->issue->issueType)) {
            $this->issue->issueType = new \stdClass();
        }

        $this->issue->issueType->name = $issueTypeName;
    }

    /**
     * Getting issue type name
     *
     * @return string issue type name
     */
    public function getIssueTypeName(): string
    {
        if (! isset($this->issue->issueType) || ! isset($this->issue->issueType->name)) {
            throw (new \Exception('Field "issueType->name" was not found for the issue'));
        }

        return $this->issue->issueType->name;
    }

    /**
     * Getting issue type
     *
     * @return object issue type
     */
    public function getIssueType(): object
    {
        if (! isset($this->issue->issueType)) {
            throw (new \Exception('Field "issueType" was not found for the issue'));
        }

        return $this->issue->issueType;
    }

    /**
     * Method creates issue
     */
    public function create(): void
    {
        $this->getConnection()->sendPostRequest('/issue', [
            'fields' => [
                'project' => $this->getProject(),
                'summary' => $this->getSummary(),
                'description' => $this->getDescription(),
                'issuetype' => $this->getIssueType()
            ]
        ]);
    }
Enter fullscreen mode Exit fullscreen mode

And now we are ready to create issue:

// connecting to your JIRA instance
$jira = new Connection('jira-url', 'jira-login', 'jira-access-token');

// setting issue data
$issue = new Issue($jira);
$issue->setSummary('summary');
$issue->setDescription('description');
$issue->setProjectKey('AP');// or any other project key of yours
$issue->setIssueTypeName('Task');// or Bug

// creating issue
$issue->create();
Enter fullscreen mode Exit fullscreen mode

And that's all! )

Links

It will be great if you will contribute something to this project. Documentation, sharing the project in your social media, bug fixing, refactoring, or even submitting issue with question or feature request. Thanks anyway )

AWS Industries LIVE! Stream

Business benefits of the cloud

Stream Industries LIVE! to explore innovative cloud solutions for modern businesses.

Learn More

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay