<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Elharem Soufiane on Medium]]></title>
        <description><![CDATA[Stories by Elharem Soufiane on Medium]]></description>
        <link>https://medium.com/@selharem?source=rss-655e0c638efb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UOC0ypPp1kILSIK7qmmpgQ.jpeg</url>
            <title>Stories by Elharem Soufiane on Medium</title>
            <link>https://medium.com/@selharem?source=rss-655e0c638efb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:27:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@selharem/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Write your first BDD using Cucumber]]></title>
            <link>https://medium.com/@selharem/write-your-first-bdd-using-cucumber-389ce16109f5?source=rss-655e0c638efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/389ce16109f5</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[gherkin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[bdd-development]]></category>
            <dc:creator><![CDATA[Elharem Soufiane]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 10:58:02 GMT</pubDate>
            <atom:updated>2024-04-25T11:45:56.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Write your first BDD tests using Cucumber</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2mdueJfaIfpbfb6A4pTvA.png" /></figure><h3>Introduction</h3><p>Hi 🤚 I’m Soufiane, a software engineer. In this article, we’re going to learn how to implement the <strong>BDD </strong>(Behavior-Driven Development) process using a tool called <strong>Cucumber </strong>in Java. So, for that, you’ll just need a working Java environment and an installed IDE.</p><h3>Behavioral-Driven Development</h3><p>Behavior-Driven Development (BDD) fosters collaboration among different stakeholders in software development, including developers and product owners. It achieves this by creating a shared understanding of the system’s behavior through the definition of common scenarios.</p><p>In a standard approach, the product owner typically provides specifications for a feature, often documented in a tool like Jira, and assigns the ticket to developers. The developers then analyze the requirements to gain a clear understanding of the feature before proceeding with implementation. Once the development is complete, testers review the code and perform testing to ensure that it meets the specified requirements. Then, the rest of the process (merge, deploy) follows.</p><p>In the BDD approach, however, they define together user stories or scenarios using a structured language, which captures the desired behavior of the system from the perspective of end users. These scenarios or behaviors serve as executable specifications that drive development, hence the term Behavioral-Driven Development. Developers then work iteratively to implement those scenarios. We start with a failing scenario, implement the minimum to make it pass, then refactor and create additional scenarios and features until development is complete. This allows for shorter feedback loops between the product owner, tester, and developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*3waEIq0s-GDXIZixlZSyLQ.png" /><figcaption>BDD process</figcaption></figure><h3>Cucumber</h3><p>Now, to implement BDD, we use tools like <strong>Cucumber</strong>. It enables us to implement BDD using a natural language syntax called <strong>Gherkin</strong>, which we will learn about in the following sections. There are other alternatives to Cucumber such as <strong>SpecFlow </strong>for .NET, Behave for Python, <strong>Gauge</strong>, etc. They all follow the same principle.</p><h3>Getting started</h3><p>We start by creating an empty Cucumber project. I am going to use IntelliJ IDEA in this blog, but the same steps apply to any other IDEs like Eclipse or VS Code. You can create a Cucumber project by running the following command in the terminal :</p><pre>mvn archetype:generate                        \<br>   &quot;-DarchetypeGroupId=io.cucumber&quot;           \<br>   &quot;-DarchetypeArtifactId=cucumber-archetype&quot; \<br>   &quot;-DarchetypeVersion=7.16.1&quot;                \<br>   &quot;-DgroupId=CucumberDemo&quot;                   \<br>   &quot;-DartifactId=CucumberDemo&quot;                \<br>   &quot;-Dpackage=CucumberDemo&quot;                   \<br>   &quot;-Dversion=1.0.0-SNAPSHOT&quot;                 \<br>   &quot;-DinteractiveMode=false&quot;</pre><p>This command creates a new Maven project based on the Cucumber archetype.</p><p>You can also create an empty Java project and then add the necessary files and dependencies.</p><p>Once the project is generated, you’ll find an example of a Cucumber project that runs well, with the following structure:</p><pre>projectName<br>├── src<br>│   │<br>│   └── test<br>│       ├── java<br>│       │   └── CucumberDemo<br>│       │       ├── RunCucumberTest.java<br>│       │       └── StepDefinitions.java<br>│       └── resources<br>│           └── CucumberDemo<br>│               └── example.feature<br>└── pom.xml</pre><p>Delete the two files <strong>example.feature</strong> and <strong>StepDefinitions </strong>because we’re going to create our own files.</p><p>To start writing a BDD test, we need two things:</p><p><strong>1. A feature file :</strong> This file is responsible for describing the feature we want to develop.<br><strong>2. A StepDefinition file :</strong> It’s a class that’s responsible for the actual behavior of the feature.</p><p>We’re going to start by describing our feature. In our case, we’re trying to build a simple game of finding a lucky number. We generate a random number, and if that number is a lucky number (for our case, it’s the number 3), we’re lucky; otherwise, we’re unfortunate. It’s a simple game, isn’t it? Maybe it’s not that exciting, but you can build whatever you want, maybe a CS:GO game with that approach.</p><h3>Creating a feature file</h3><p>In the directory <strong>resources/(project name)/features</strong>, we create a feature file <strong>lucky-number</strong> with the extension <strong>.feature</strong>. We add it to the <strong>features </strong>folder because our application will consist of multiple features, not just one!</p><p>Our feature file will look like this :</p><pre>Feature: Finding the lucky number<br><br>  Scenario : Get lucky number<br>    Given a random number is generated as 1<br>    When I verify if the lucky number is 3<br>    Then I expect to receive the answer&quot;Unfortunate&quot;</pre><p>This file describes our feature using <strong>Gherkin </strong>syntax. It’s a language used by product teams to define requirements for developers to implement using Cucumber. We define our feature with the keyword ‘<strong>Feature</strong>’ followed by a brief description, such as ‘finding the lucky number.’ Next, we create scenarios using the keyword ‘<strong>Scenario</strong>.’ Within a single feature file, we can include multiple scenarios. In our case, we’ll start with a simple scenario: ‘Get lucky number with simple rules.’ In this scenario, we select the number 1, which doesn’t match the lucky number 3, resulting in the user receiving ‘Unfortunate’ as the outcome.</p><p>As we’ve implemented our first scenario, let’s test it. Run the following command in the terminal.</p><pre>mvn test</pre><p>Then, you’ll encounter an error:</p><pre>[ERROR] Errors: <br>[ERROR]   The step &#39;a random number is generated as 1&#39; and 2 other step(s) are undefined.<br>You can implement these steps using the snippet(s) below:<br><br>@Given(&quot;a random number is generated as 1&quot;)<br>public void a_random_number_is_generated_as_1(Integer int1) {<br>    // Write code here that turns the phrase above into concrete actions<br>    throw new io.cucumber.java.PendingException();<br>}<br>@When(&quot;I verify if the lucky number is 3&quot;)<br>public void i_verify_if_the_lucky_number_is_3() {<br>    // Write code here that turns the phrase above into concrete actions<br>    throw new io.cucumber.java.PendingException();<br>}<br>@Then(&quot;I expect to receive the answer {string}&quot;)<br>public void i_expect_to_receive_the_answer(String string) {<br>    // Write code here that turns the phrase above into concrete actions<br>    throw new io.cucumber.java.PendingException();<br>}</pre><p>By default, Cucumber scans the entire classpath for step definitions. In large projects, this can be inefficient, so it’s better to configure the glue path. You’re essentially telling Cucumber to look for step definitions in specific packages or directories. Since we only use one feature file, there’s no need for it.</p><p>The error occurs because we haven’t defined our steps yet.</p><h3>Creating step definition</h3><p>Let’s define our steps now. Copy the methods thrown in the error and paste them into a newly created class</p><p><strong><em>src/test/java/CucumberDemo/FindingTheLuckyNumber.java</em></strong></p><pre>package CucumberDemo;<br><br>import io.cucumber.java.en.Given;<br>import io.cucumber.java.en.Then;<br>import io.cucumber.java.en.When;<br><br>public class FindingTheLuckyNumber {<br>  @Given(&quot;a random number is generated as 1&quot;)<br>  public void a_random_number_is_generated_as_1(Integer int1) {<br>     // Write code here that turns the phrase above into concrete actions<br>     throw new io.cucumber.java.PendingException();<br>  }<br><br>  @When(&quot;I verify if the lucky number is 3&quot;)<br>  public void i_verify_if_the_lucky_number_is_3() {<br>      // Write code here that turns the phrase above into concrete actions<br>      throw new io.cucumber.java.PendingException();<br>  }<br><br>  @Then(&quot;I expect to receive the answer {string}&quot;)<br>  public void i_expect_to_receive_the_answer(String string) {<br>      // Write code here that turns the phrase above into concrete actions<br>      throw new io.cucumber.java.PendingException();<br>  }<br>}</pre><p>Run cucumber again, you’ll see that error :</p><pre>1 Scenarios (1 pending)<br>3 Steps (2 skipped, 1 pending)</pre><h3>Implementing step definition</h3><p>Now, tests are pending. You should implement the steps so that the tests can pass.</p><pre>package CucumberDemo;<br><br>import io.cucumber.java.en.Given;<br>import io.cucumber.java.en.Then;<br>import io.cucumber.java.en.When;<br><br>import static org.junit.jupiter.api.Assertions.assertEquals;<br><br>public class FindingTheLuckyNumber {<br><br>    private int randomNumber;<br>    private String answer;<br>    private static final int LUCKY_NUMBER = 3;<br><br>    @Given(&quot;a random number is generated as 1&quot;)<br>    public void a_random_number_is_generated_as_1() {<br>        this.randomNumber = 1;<br>    }<br>    <br>    @When(&quot;I verify if the lucky number is 3&quot;)<br>    public void i_verify_if_the_lucky_number_is_3() {<br>        answer = null;<br>    }<br>    <br>    @Then(&quot;I expect to receive the answer {string}&quot;)<br>    public void i_expect_to_receive_the_answer(String expectedAnswer) {<br>        assertEquals(expectedAnswer, answer);<br>    }<br>}</pre><p>When you run Cucumber, you’ll have:</p><pre>Failed scenarios:<br>src/test/resources/CucumberDemo/features/lucky_number.feature:3 # Finding the lucky number<br>1 Scenarios (1 failed)<br>3 Steps (1 failed, 2 passed)</pre><p>So, one of the 3 steps failed. It’s the third one. You should follow the BDD process and write the minimal code to make it pass.</p><pre>package CucumberDemo;<br><br>import io.cucumber.java.en.Given;<br>import io.cucumber.java.en.Then;<br>import io.cucumber.java.en.When;<br><br>import static org.junit.jupiter.api.Assertions.assertEquals;<br><br>public class FindingTheLuckyNumber {<br><br>    private int randomNumber;<br>    private String answer;<br>    private static final int LUCKY_NUMBER = 3;<br><br>    @Given(&quot;a random number is generated as 1&quot;)<br>    public void a_random_number_is_generated_as_1() {<br>        this.randomNumber= 1;<br>    }<br>    <br>    @When(&quot;I verify if the lucky number is 3&quot;)<br>    public void i_verify_if_the_lucky_number_is_3() {<br>        answer = &quot;Unfortunate&quot;;<br>    }<br>    <br>    @Then(&quot;I expect to receive the answer {string}&quot;)<br>    public void i_expect_to_receive_the_answer(String expectedAnswer) {<br>        assertEquals(expectedAnswer, answer);<br>    }<br>}</pre><p>Run Cucumber again</p><pre>1 Scenarios (1 passed)<br>3 Steps (3 passed)</pre><p>All three of our steps have passed. Now, let’s take a moment to refactor our method names to align with our coding style.</p><p>We’ll rename them as follows: <strong><em>generateRandomNumber</em></strong>, <strong><em>askIfNumberIsLucky</em></strong>, and <strong><em>verifyLuckyNumberResponse</em></strong>.</p><p>Moving forward, we aim to enhance the versatility of our code. We’ll achieve this by generalizing the generated number and response by introducing two variables.</p><h3>Adding variables</h3><pre>Feature: Finding the lucky number<br><br>  Scenario : Get lucky number<br>    Given a random number is generated &lt;randomNumber&gt;<br>    When I verify if the generated number is the lucky number<br>    Then I expect to receive the answer &quot;&lt;expectedAnswer&gt;&quot;</pre><p>Additionally, we’ll incorporate examples to illustrate our changes effectively. That improves understanding of the feature and also covers outline cases, if any. To enable this, we need to modify <strong><em>Scenario</em></strong> to <strong><em>Scenario Outline</em></strong> :</p><h3>Adding examples</h3><pre>Feature: Finding the lucky number<br><br>  Scenario Outline : Get lucky number<br>    Given a random number is generated &lt;randomNumber&gt;<br>    When I verify if the generated number is the lucky number<br>    Then I expect to receive the answer &quot;&lt;expectedAnswer&gt;&quot;<br>    <br>  Examples:<br>    | randomNumber | expectedAnswer |<br>    | 1            | Unfortunate    |<br>    | 2            | Unfortunate    |<br>    | 3            | Lucky          |</pre><p>The steps are going to fail. This is normal. As previously, you should implement them so they can pass with the minimum code.</p><pre>package CucumberDemo;<br><br>import io.cucumber.java.en.Given;<br>import io.cucumber.java.en.Then;<br>import io.cucumber.java.en.When;<br><br>import static org.junit.jupiter.api.Assertions.assertEquals;<br><br>public class FindingTheLuckyNumber {<br><br>    private int randomNumber;<br>    private String answer;<br>    private static final int LUCKY_NUMBER = 3;<br><br>    @Given(&quot;a random number is generated {int}&quot;)<br>    public void generatingARandomNumber(int randomNumber) {<br>        this.randomNumber = randomNumber;<br>    }<br><br>    @When(&quot;I check if the generated number is the lucky number&quot;)<br>    public void iCheckWeitherIFindTheLuckyNumber() {<br>        answer = (randomNumber == LUCKY_NUMBER) ? &quot;Lucky&quot; : &quot;Unfortunate&quot;;<br>    }<br><br>    @Then(&quot;I should be told {string}&quot;)<br>    public void iShouldBeTold(String expectedAnswer) {<br>        assertEquals(expectedAnswer, answer);<br>    }<br>}</pre><p>Tests are going to pass now.</p><pre>1 Scenarios (1 passed)<br>3 Steps (3 passed)</pre><h3>Conclusion</h3><p>If you’ve reached this step, congratulations 🥳! You’ve just completed your first BDD test. Of course, if you’re serious about using Cucumber and BDD, you’ll be building more complex and useful applications instead of a simple program. So, you should create more scenarios and features, resulting in more step definitions. The same process applies :</p><p>write a scenario → write step definitions → fail the test → write the minimum code to pass the test → refactor → repeat.</p><p>If you want to learn more about using Cucumber, visit the official documentation at <a href="https://cucumber.io/docs">https://cucumber.io/docs</a>.</p><p>You can find the source code of this app in the following repo :</p><p><a href="https://github.com/Selharem/CucumberDemo">https://github.com/Selharem/CucumberDemo</a></p><p>If you find this post useful, make sure to follow me on:</p><ul><li><strong>Github</strong>: <a href="https://github.com/Selharem">github/Selharem</a></li><li><strong>Medium</strong> : <a href="https://medium.com/@selharem">medium/@selharem</a></li><li><strong>linkedIn </strong>: <a href="https://www.linkedin.com/in/elharem-soufiane/">linkedin/in/elharem-soufiane</a></li></ul><p>Thank you for reading. See you in another blog ✋.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=389ce16109f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API design 101 : build a nodejs REST microservice using GITHUB APIs]]></title>
            <link>https://medium.com/@selharem/api-design-101-build-a-nodejs-rest-microservice-using-github-apis-3d563af71ce0?source=rss-655e0c638efb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d563af71ce0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Elharem Soufiane]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 00:46:19 GMT</pubDate>
            <atom:updated>2024-04-17T10:51:21.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>API design 101 : build a nodejs REST microservice using GITHUB APIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjEn_jvcyi5NTeBEdM2tNQ.png" /></figure><h3><strong>Introduction</strong></h3><p>APIs (Application Programming Interface) are a way to enable communication between different application components in one hand and between our application and other applications in the other hand.</p><p>A microservice is a small, single service that can be delivered through an API.</p><p>In this article, we will create a REST microservice that lists the languages used by the trending public Github repos in the last 30 days.</p><p>We’re gonna have two <strong>endpoints </strong>:</p><ul><li><strong>(GET) /api/repos <em>: </em></strong>returns the trending repos in the last 30 days from now.</li><li><strong>(GET)/api/repos/{date} : </strong>returns the trending repos in the last 30 days from the given date.</li></ul><p>We have to calculate the total number of repos, and for each language we have to return :</p><ul><li>The number of repos using the language.</li><li>The list of repos using the language.</li></ul><p>Note that a trending repo is a most starred repo.</p><h3><strong>Tools </strong>used</h3><ul><li><a href="https://nodejs.org/en/">Nodejs </a>: JavaScript runtime environment.</li><li><a href="https://expressjs.com/">Express.js</a><strong> </strong>: web framework built on the top of nodejs, we will use it to build our server.</li><li><a href="https://axios-http.com/">Axios</a><strong> </strong>: promise based HTTP client for the browser and node.js, we will use it to fetch data from the GITHUB API.</li><li><a href="https://code.visualstudio.com/">VScode </a>: modern code editor.</li><li><a href="https://www.postman.com/">Postman </a>: HTTP client to test our API.</li></ul><p>Let’s jump in to create our API.</p><h3>Project structure</h3><p>To build our API, we need three things :</p><ul><li><strong>Routes </strong>: used to forward HTTP requests to the appropriate controller functions. We will have two routes in our API :<br>- <strong>reposRouter :</strong> repos route without specifying the date. <strong><br>- reposWithDateRouter : </strong>repos route with a specific date.</li><li><strong>Controllers</strong> : Receives the requests and fetch data from the Github API, then returns the response.</li><li><strong>main file</strong> : This file will expose our routes to the user and starts the server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cvlbqg_Sy227j9K7EKViw.png" /><figcaption><strong>Project architecture</strong></figcaption></figure><p>The project structure is gonna be like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*zhQQkqOnE7EfZ1-xvdRsEw.png" /><figcaption><strong>Project structure</strong></figcaption></figure><h3>Github APIs</h3><p>Github APIs (or Github REST APIs) are APIs to interact with Github and fetch informations like users, repositories, and pull requests. In our case, we will use <a href="https://docs.github.com/en/rest/reference/search"><strong>GitHub Search API</strong></a> to display informations about repositories.</p><p>To fetch the trending repos, we need to call the following endpoint :</p><pre>https://api.github.com/search/repositories?q=created:&gt;{date}&amp;sort=stars&amp;order=desc</pre><p>And replace <strong>date</strong> with a <strong>YYYY-MM-DD </strong>date format.</p><p>The received data will be paginated, there’s no need to get the subsequent pages.</p><p>Now let’s move on to the realisation.</p><h3>Getting started</h3><p>Here are the steps to create our API :</p><ol><li>Installing the Node packages.</li><li>Create our server using Express.js.</li><li>Declare our routes using Express.Router.</li><li>Create our controller function.</li><li>Testing our API using Postman.</li></ol><h3>Installing the Node packages</h3><p>We will define the packages we need in <strong>package.json</strong> file :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59012a89642c09dd280a822b73d28b3c/href">https://medium.com/media/59012a89642c09dd280a822b73d28b3c/href</a></iframe><p>What do these packages do ? <strong>axios </strong>is<strong> </strong>a promise based HTTP client used to fetch data from distant endpoints. <strong>dotenv </strong>is an npm module that loads environment variables from a .env file. <strong>express </strong>is the Node framework<strong>. moment </strong>is a javascript date library, we will use it to format our dates to the YYYY-MM-DD<strong> </strong>format. <strong>morgan</strong> is a middleware for logging incoming requests. <strong>nodemon </strong>is a command-line interface (CLI) that restarts our server on save.</p><p>Go ahead and create a<strong> package.json</strong> file with the given dependencies in the root directory, then run the following command :</p><pre>npm install</pre><p>We will be creating our<strong> app.json</strong> file to set up our server, since that’s our main file declared in <strong>package.json.</strong></p><h3>Create the server</h3><p>Here’s our <strong>app.js </strong>file where we will start our server and import our routes :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/298c4a965ac686781fa916e33a15413c/href">https://medium.com/media/298c4a965ac686781fa916e33a15413c/href</a></iframe><ul><li>Base setup : In the beginning, we imported our needed packages : <strong>express</strong>, <strong>dotenv</strong>, <strong>morgan </strong>and our routes’ file <strong>./Routes/repos</strong> where we will define our two routes. Then we set the port, define our app using express and call morgan with dev parameter, that will give us the simplest amount of information needed for our development lifecycle.</li><li>Using our middleware function : <strong>use() </strong>function uses the specified middleware function, <strong>reposRoutes </strong>and <strong>reposWithDateRoutes</strong></li></ul><p>Start the server: we’ll have our express app listen to our predefined port.</p><p>When you run the server with <strong>npm start, </strong>you’ll get an error. We didn’t define our routes yet.</p><p>Let’s do this now.</p><p>Don’t forget to create a<strong> .env </strong>file in the root directory with a port value :</p><pre>PORT = 5000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*6vd63WhHPdfVTAHoPe_WZQ.png" /><figcaption><strong>.env</strong></figcaption></figure><h3>Declare our routes</h3><p>Instead of defining our routes in the main file<strong> app.js</strong>, we will use Express Router middleware. It’s good practice to declare your routes in a separate file. For our simple API, it’s not a big deal, but when you want to scale your app then you’ll have a problem in managing your routes. The Express Router gives us a great flexibility in defining our routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2fa3fd2d5d2e1f70c585a6ebf78eec/href">https://medium.com/media/3d2fa3fd2d5d2e1f70c585a6ebf78eec/href</a></iframe><ul><li>In the beginning, we imported express and our controller <strong>getRepos. </strong>Then, we got two instances for our two routes of the express Router.</li><li>Then, we’ll use our routes to make a GET request to the given endpoints : <strong>http://localhost:5000/api/repos</strong> to get the trending languages in the last 30 days and <strong>http://localhost:5000/api/repos/{date} </strong>to get the trending languages in the last 30 days from the given date. We will define a controller function to handle the requests. It’s a good practice, you’d better get used to it.</li><li>Finally, don’t forget to export the routes, so that you can use them, in our case, inside the <strong>app.js</strong> file.</li></ul><p>Now let’s define our controller function.</p><h3>Create our controller function</h3><p>Although we have two routes, we will use only one controller function. We can separate them into two functions, but then we will be duplicating our implementation. You’ll see that we can create a controller function for both routes, depending on whether the date is passed in the URL or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db37d0cad864aecf13167958b65ef92/href">https://medium.com/media/6db37d0cad864aecf13167958b65ef92/href</a></iframe><p>As always, in the beginning, we imported our needed packages : <strong>express </strong>and <strong>axios. </strong>The function <strong>getRepos()</strong> receive a request and return a response.</p><p>I used a lot of helper functions that I created to separate responsibilities and to make the code more cleaner. You can find them at <strong>root_folder/utils/utils.js.</strong></p><p>I will add their implementations later in this blog.</p><p><strong>getDate() </strong>returns the date object passed in parameter, if it’s the case, in the <strong>YYYY-MM-DD </strong>format. If the date is not passed in parameter (the user called the first endpoint) then it’s today’s date that’s formatted.</p><p>The result of the request to that Github endpoint (<strong>url</strong>) will be in the following format :</p><pre>{</pre><pre>    total_count: &quot;number&quot;,</pre><pre>    incomplete_results: &quot;boolean&quot;,</pre><pre>    items: [</pre><pre>    {</pre><pre>      ...</pre><pre>        &quot;name&quot;: &quot;X&quot;,</pre><pre>      ...</pre><pre>        &quot;language&quot;: &quot;languageX&quot;,</pre><pre>    },</pre><pre>      ...</pre><pre>    {</pre><pre>      ...</pre><pre>        &quot;name&quot;: &quot;Y&quot;,</pre><pre>      ...</pre><pre>        &quot;language&quot;: &quot;null&quot;},</pre><pre>    ]</pre><pre>}</pre><p>For our API, we need the repos with non null languages.</p><p>After calling axios with the method<strong> axios.get(url), </strong>we store the repos with defined languages in the <strong>repos </strong>array using the function <strong>pushNonNullRepos.</strong></p><p>Now, the <strong>repos </strong>array contains objects with two properties : <strong>name </strong>and <strong>language :</strong></p><pre><strong>[</strong></pre><pre>  {</pre><pre>    &quot;name&quot;: &quot;repo1&quot;,</pre><pre>    &quot;language&quot;: &quot;language1&quot;,</pre><pre>  },</pre><pre>  ...</pre><pre>  {</pre><pre>    &quot;name&quot;: &quot;repoN&quot;,</pre><pre>    &quot;language&quot;: &quot;languageN&quot;,</pre><pre>  }</pre><pre><strong>]</strong></pre><p>We need to gather all the repos with the same language and count the number of repos for each language as well as the number of total repos. Each object will have three properties : <strong>language</strong>, <strong>number of repos </strong>and<strong> repos. </strong>The desired output will look like this :</p><pre><strong>{</strong></pre><pre>  &quot;total_count&quot;: xx,<br>  &quot;result&quot;: <strong>[</strong><br>     <strong>{</strong><br>         &quot;language&quot;: &quot;languageX&quot;,</pre><pre>         &quot;number of repos&quot;: x,</pre><pre>         &quot;repos &quot;: <strong>[</strong></pre><pre>             &quot;repo1&quot;,</pre><pre>                 ...</pre><pre>             &quot;repoN&quot;</pre><pre><strong>         ]</strong></pre><pre>     <strong>}</strong>,<br>        ...</pre><pre>  <strong>]</strong></pre><pre><strong>}</strong></pre><p>It’s the purpose of <strong>getTrendingRepos </strong>function<strong>, </strong>it takes as parameter an array of unique languages, that’s why we removed duplicates in <strong>languages, </strong>and the <strong>repos </strong>array. Inside the function, we will create an array that gathers for each language the list of repos using it. So that <strong>repos</strong> property will have that list as a value, and its length as a value of <strong>number of repos’ </strong>property. At the end, our function will return an object with the desired format, after adding the <strong>total_count </strong>property.</p><p>Our <strong>utils.js</strong> file will look like this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ad993f42e5760f6618a4b357280a1b8/href">https://medium.com/media/8ad993f42e5760f6618a4b357280a1b8/href</a></iframe><h3>Testing the API</h3><p>Now, as our API is ready, we can start the server using the following command in the root directory :</p><pre>nodemon app.js</pre><p>Let’s test our API in Postman :</p><ul><li>We’ll try with the default endoint, without specifying the date (the date of request : <strong>2021–12–27</strong>) :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*NNaGR96wZr5DhpC0_6XLSw.png" /></figure><ul><li>Now we’ll try with a given date (for ex. <strong>2021–07–29</strong>) :</li></ul><p>So we need to call this endpoint :</p><pre>http://localhost:5000/api/repos/2021-08-29</pre><p>And we’ll get the following result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*JTZAWJSVdhlpBOZvbwCPyQ.png" /></figure><h3>Conclusion</h3><p>This has been a quick look into creating a simple API with nodejs and Express 4. You can go further and create the frontend for this API, a beautiful UI with a list of repos and a search bar will be good.</p><p>You can find the source code of this app in the following repo :</p><p><a href="https://github.com/Selharem/Express-Github-API">github/Selharem/Express-Github-API</a></p><p>If you enjoyed this post, make sure to follow me on:</p><ul><li><strong>Github</strong>: <a href="https://github.com/Selharem">github/Selharem</a></li><li><strong>Medium</strong> : <a href="https://medium.com/@selharem">medium/@selharem</a></li><li><strong>linkedIn </strong>: <a href="https://www.linkedin.com/in/elharem-soufiane/">linkedin/in/elharem-soufiane/</a></li><li><strong>Twitter</strong> : <a href="https://twitter.com/selharem">twitter/selharem</a></li></ul><p>Thank you for reading. See you in another blog ✋.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d563af71ce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>