<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Andisi (Roseland) Ambuku</title>
    <description>The latest articles on DEV Community by Andisi (Roseland) Ambuku (@andisiambuku).</description>
    <link>https://dev.to/andisiambuku</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F809906%2F18d889bd-bf92-4e80-84a7-1b2f569d0c37.jpg</url>
      <title>DEV Community: Andisi (Roseland) Ambuku</title>
      <link>https://dev.to/andisiambuku</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/andisiambuku"/>
    <language>en</language>
    <item>
      <title>How to Integrate GraphQL in Next JS using Apollo Client</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Wed, 13 Nov 2024 08:36:59 +0000</pubDate>
      <link>https://dev.to/andisiambuku/how-to-integrate-graphql-in-next-js-using-apollo-client-240p</link>
      <guid>https://dev.to/andisiambuku/how-to-integrate-graphql-in-next-js-using-apollo-client-240p</guid>
      <description>&lt;h2&gt;
  
  
  Introduction to GraphQL
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;GraphQL&lt;/strong&gt; is an API query language that fetches data based only on what the client application needs. It solves the problem of clients fetching unnecessary data thus making APIs more scalable. The precision in data fetching is the power of GraphQL. Find out more on the official &lt;a href="https://graphql.org/" rel="noopener noreferrer"&gt;GraphQL website&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this tutorial, we will learn how to work with Apollo Client, a JavaScript state management library that assists you manage GraphQL both remotely and locally. We shall learn to use it on the client side and server side in Next JS apps.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting Up the Project
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://nodejs.org/" rel="noopener noreferrer"&gt;Node.js 18.18&lt;/a&gt; or later.&lt;/li&gt;
&lt;li&gt;Knowledge of GraphQL and how it works. Find out more on the official &lt;a href="https://graphql.org/" rel="noopener noreferrer"&gt;GraphQL website&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Next JS 14 or later.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Type this command in your terminal to create a new project.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx create-next-app@latest&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;When installing, you will see the following prompts. Ensure you choose the App Router.
What is your project named? graphql-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like your code inside a `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to use Turbopack for `next dev`?  No / Yes
Would you like to customize the import alias (`@/*` by default)? No / Yes
What import alias would you like configured? @/*
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Installing Dependencies
&lt;/h3&gt;

&lt;p&gt;As mentioned, we shall learn data-fetching in server and client components. Apollo Client provides an experimental library to facilitate this. Install the following dependencies.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install @apollo/client @apollo/experimental-nextjs-app-support&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Server Components
&lt;/h2&gt;

&lt;p&gt;We shall begin with data fetching from a GraphQL API in server components.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating the Apollo Client Instance
&lt;/h3&gt;

&lt;p&gt;Firstly, we will create an Apollo Client instance that we shall use throughout our app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ./ApolloClient
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { registerApolloClient } from "@apollo/experimental-nextjs-app-support";

export const { getClient } = registerApolloClient(() =&amp;gt; {
  return new ApolloClient({
    cache: new InMemoryCache({ addTypename: false }),
    link: new HttpLink({
      uri: "https://rickandmortyapi.com/graphql",
    }),

  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s break it down step by step:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;registerApolloClient: This function takes a callback which initializes and returns an instance of Apollo Client. This is specifically for Next JS since it allows use with the framework’s server-side rendering (SSR).&lt;/li&gt;
&lt;li&gt;Apollo Client Configuration: The configuration for Apollo Client is done inside the callback function passed to registerApolloClient.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;cache: new InMemoryCache({ addTypename: false }),&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Initializes an InMemoryCache for data storage and management of GraphQL queries.&lt;/li&gt;
&lt;li&gt;addTypename: false: ensures the response from the query does not have the _typename in the result. It makes it easier to display the result in the front end.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;link: new HttpLink({
 uri: “https://rickandmortyapi.com/graphql",
 }),

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Establishes an HTTP link that Apollo Client uses to send queries to the endpoint we specify.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create this file in the root of your Next JS app folder so that the instance is available to all pages in the app router.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating the query
&lt;/h3&gt;

&lt;p&gt;Next, we shall create the query that fetches the data we wish to display in our Next JS app. Create a folder at the project’s root called queries where the queries will be stored.&lt;/p&gt;

&lt;p&gt;Create a file called &lt;em&gt;characterQuery&lt;/em&gt; and paste the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { gql } from "@apollo/client";


export const characterQuery = gql`
  query {
    characters {
      results {
        name
        status
        species
        image
        origin {
          name
        }
        location {
          name
        }
      }
    }
  }
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code defines the character query which requests the characters from the endpoint with specific fields with data about the characters.&lt;/p&gt;

&lt;p&gt;The data from the query is rendered in the component below. Let us discuss what the code does.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { getClient } from "./ApolloClient";
import Image from 'next/image'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { characterQuery } from "@/queries/characterQuery";
import { Character, CharacterQueryResponse } from "@/types/types";



export default async function Home() {
  const { data } = await getClient().query&amp;lt;CharacterQueryResponse&amp;gt;({ query: characterQuery });

  return (
    &amp;lt;div className="flex min-h-screen flex-col items-center justify-between p-24"&amp;gt;
      &amp;lt;div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"&amp;gt;
        {data.characters.results.map((character:Character, index:number) =&amp;gt;  (
          &amp;lt;Card key={index} className="max-w-sm mx-auto my-4"&amp;gt;
            &amp;lt;CardHeader className="relative"&amp;gt;
              &amp;lt;Image src={character.image} width={300} height={300} alt={character.name} /&amp;gt;
              &amp;lt;Button className="absolute right-2 top-2"&amp;gt;{character.status}&amp;lt;/Button&amp;gt;
              &amp;lt;CardTitle&amp;gt;{character.name}&amp;lt;/CardTitle&amp;gt;
            &amp;lt;/CardHeader&amp;gt;
            &amp;lt;CardContent&amp;gt;
              &amp;lt;p&amp;gt;{character.species}&amp;lt;/p&amp;gt;
              &amp;lt;p&amp;gt;Origin: {character.origin.name}&amp;lt;/p&amp;gt;
              &amp;lt;p&amp;gt;Location: {character.location.name}&amp;lt;/p&amp;gt;
            &amp;lt;/CardContent&amp;gt;
          &amp;lt;/Card&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We begin by fetching the data.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const { data } = await getClient().query&amp;lt;CharacterQueryResponse&amp;gt;({ query: characterQuery });&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;getClient().query({ query: characterQuery }) calls the Apollo Client instance’s query method passing in characterQuery to fetch character data from the API.&lt;/li&gt;
&lt;li&gt;The data is rendered in the form of cards. Feel free to play around with the styling.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjr1ypo1pg1er0w4s71kk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjr1ypo1pg1er0w4s71kk.png" alt="Image description" width="800" height="568"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Client Components
&lt;/h2&gt;

&lt;p&gt;This data fetching method applies to client components, in the event you wish to use state or context depending on your use case.&lt;/p&gt;

&lt;p&gt;We begin by creating a provider for Apollo that passes the client to the hooks.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ./apollo-wrapper.tsx

"use client";

import { ApolloLink, HttpLink } from "@apollo/client";
import {
  ApolloClient,
  ApolloNextAppProvider,
  InMemoryCache,
  SSRMultipartLink,
} from "@apollo/experimental-nextjs-app-support";


function makeClient() {
  const httpLink = new HttpLink({
    uri: "https://rickandmortyapi.com/graphql",
  });

  return new ApolloClient({
    cache: new InMemoryCache(),
    link:
      typeof window === "undefined"
        ? ApolloLink.from([
            // in a SSR environment, if you use multipart features like
            // @defer, you need to decide how to handle these.
            // This strips all interfaces with a `@defer` directive from your queries.
            new SSRMultipartLink({
              stripDefer: true,
            }),
            httpLink,
          ])
        : httpLink,
  });
}

export function ApolloWrapper({ children }: React.PropsWithChildren) {
  return (
    &amp;lt;ApolloNextAppProvider makeClient={makeClient}&amp;gt;
      {children}
    &amp;lt;/ApolloNextAppProvider&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s break it down step by step:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We create an HTTP link that Apollo Client uses to send queries to the endpoint we specify&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then we define a function called makeClient which creates an Apollo Client instance for SSR and client environments.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function makeClient() {
  const httpLink = new HttpLink({
    uri: "https://rickandmortyapi.com/graphql",
  });

  return new ApolloClient({
    cache: new InMemoryCache(),
    link:
      typeof window === "undefined"
        ? ApolloLink.from([
            // in a SSR environment, if you use multipart features like
            // @defer, you need to decide how to handle these.
            // This strips all interfaces with a `@defer` directive from your queries.
            new SSRMultipartLink({
              stripDefer: true,
            }),
            httpLink,
          ])
        : httpLink,
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;SSRMultipartLink: A link specifically designed for handling multipart responses in SSR.&lt;/li&gt;
&lt;li&gt;stripDefer: true: Strips interfaces with &lt;a class="mentioned-user" href="https://dev.to/defer"&gt;@defer&lt;/a&gt; directives from queries.&lt;/li&gt;
&lt;li&gt;The &lt;a class="mentioned-user" href="https://dev.to/defer"&gt;@defer&lt;/a&gt; Directive, when enabled, allows portions of a query to load separately for faster page rendering. Stripping it for SSR simplifies processing, especially since SSR environments may not handle &lt;a class="mentioned-user" href="https://dev.to/defer"&gt;@defer&lt;/a&gt; the same way as the client.&lt;/li&gt;
&lt;li&gt;The link configuration has a condition for SSR and client environments where the link is used directly in client environments.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function ApolloWrapper({ children }: React.PropsWithChildren) {
  return (
    &amp;lt;ApolloNextAppProvider makeClient={makeClient}&amp;gt;
      {children}
    &amp;lt;/ApolloNextAppProvider&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the layout file, we shall add the Apollo Wrapper.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ./layout

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ApolloWrapper } from "./apollo-wrapper";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Rick &amp;amp; Morty App",
  description: "GraphQL Demo app",
};

export default function RootLayout({
  children,
}: Readonly&amp;lt;{
  children: React.ReactNode;
}&amp;gt;) {
  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;ApolloWrapper&amp;gt;
      &amp;lt;body className={inter.className}&amp;gt;{children}&amp;lt;/body&amp;gt;
      &amp;lt;/ApolloWrapper&amp;gt;
    &amp;lt;/html&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then use the Apollo Wrapper we created above to wrap the body of the content which ensures that all pages have Apollo Client access.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ./page.tsx

'use client'

import { Character, CharacterQueryResponse } from "@/types/types";
import Image from 'next/image'
import {  useSuspenseQuery } from '@apollo/client';
import { characterQuery } from '@/queries/characterQuery';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

export default function Home() {

  const { data } = useSuspenseQuery&amp;lt;CharacterQueryResponse&amp;gt;(characterQuery);

  return(
    &amp;lt;div className="flex min-h-screen flex-col items-center justify-between p-24"&amp;gt;
          &amp;lt;div className="flex min-h-screen flex-col items-center justify-between p-24"&amp;gt;
      &amp;lt;div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"&amp;gt;
        {data.characters.results.map((character:Character, index:number) =&amp;gt;  (
          &amp;lt;Card key={index} className="max-w-sm mx-auto my-4"&amp;gt;
            &amp;lt;CardHeader className="relative"&amp;gt;
              &amp;lt;Image src={character.image} width={300} height={300} alt={character.name} /&amp;gt;
              &amp;lt;Button className="absolute right-2 top-2"&amp;gt;{character.status}&amp;lt;/Button&amp;gt;
              &amp;lt;CardTitle&amp;gt;{character.name}&amp;lt;/CardTitle&amp;gt;
            &amp;lt;/CardHeader&amp;gt;
            &amp;lt;CardContent&amp;gt;
              &amp;lt;p&amp;gt;{character.species}&amp;lt;/p&amp;gt;
              &amp;lt;p&amp;gt;Origin: {character.origin.name}&amp;lt;/p&amp;gt;
              &amp;lt;p&amp;gt;Location: {character.location.name}&amp;lt;/p&amp;gt;
            &amp;lt;/CardContent&amp;gt;
          &amp;lt;/Card&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;useSuspenseQuery&lt;/em&gt; allows for streaming, as it does in SSR rendering. Here we pass in characterQuery to fetch character data from the API.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;const { data } = useSuspenseQuery&amp;lt;CharacterQueryResponse&amp;gt;(characterQuery);&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;This article discusses integrating GraphQL in Next JS using Apollo Client and GraphQL concepts related to front-end development. The project is available &lt;a href="https://github.com/andisiambuku/Rick-Morty-GraphQL" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
If you wish to discuss the topic further, contact me on &lt;a href="https://www.linkedin.com/in/roseland-ambuku/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thank you for reading! Until next time, may the code be with you.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.apollographql.com/blog/how-to-use-apollo-client-with-next-js-13#client-components" rel="noopener noreferrer"&gt;How to use Apollo Client with Next.js 13 | Apollo GraphQL Blog&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/apollographql/apollo-client-nextjs/tree/main/examples" rel="noopener noreferrer"&gt;apollo-client-nextjs/examples at main · apollographql/apollo-client-nextjs&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.apollographql.com/blog/using-apollo-client-with-next-js-13-releasing-an-official-library-to-support-the-app-router#client-components-with-server-side-rendering" rel="noopener noreferrer"&gt;Using Apollo Client with Next.js 13: releasing an official library to support the App Router | Apollo GraphQL Blog&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>nextjs</category>
      <category>graphql</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How To Create a Chart From a Dynamic Dataset in Next JS Using Chart.js</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Fri, 05 Jan 2024 14:12:36 +0000</pubDate>
      <link>https://dev.to/andisiambuku/how-to-create-a-chart-from-a-dynamic-dataset-in-next-js-using-chartjs-3gmb</link>
      <guid>https://dev.to/andisiambuku/how-to-create-a-chart-from-a-dynamic-dataset-in-next-js-using-chartjs-3gmb</guid>
      <description>&lt;p&gt;A &lt;strong&gt;chart&lt;/strong&gt; is defined as a visual representation of data, and it is important in breaking down data in a way that is simple to understand and interpret. There are various use cases for visualizations in apps e.g. ecommerce dashboards and cryptocurrency dashboards. &lt;/p&gt;

&lt;p&gt;In this tutorial, we shall learn how to create a line chart in Next JS using Chart JS. We shall build on this project that we created &lt;a href="https://dev.to/andisiambuku/creating-a-cryptocurrency-app-with-next-js-and-coin-gecko-api-b7h"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;In this tutorial we shall use the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node JS installed in your machine.&lt;/li&gt;
&lt;li&gt;Next 13 and above.&lt;/li&gt;
&lt;li&gt;The documentation for the Coin Gecko API is available &lt;a href="https://www.coingecko.com/api/documentation" rel="noopener noreferrer"&gt;here&lt;/a&gt;. Be sure to refer to the documentation whenever we use an endpoint.&lt;/li&gt;
&lt;li&gt;Tailwind CSS for styling our app.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;Chart JS is a great choice for creating charts as it has multiple visualizations. There are different integrations for the JS frameworks, and we shall use &lt;a href="https://react-chartjs-2.js.org/" rel="noopener noreferrer"&gt;react-chart-js-2&lt;/a&gt; library for Next JS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Installing Dependencies
&lt;/h3&gt;

&lt;p&gt;We shall install the dependencies by running the following command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save chart.js react-chartjs-2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Market Chart Component
&lt;/h3&gt;

&lt;p&gt;We shall create a component to handle the fetching and creation of the chart.&lt;/p&gt;

&lt;p&gt;In the Components folder, create a folder called &lt;code&gt;MarketChart.tsx&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Have the following imports at the top of your file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  Tooltip,
  PointElement,
  LineElement,
} from "chart.js";
import { useEffect, useState } from "react";
import { Line } from "react-chartjs-2";

// Register ChartJS components using ChartJS.register
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Tooltip
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is imperative to register the correct elements for the chart you are creating, refer to the &lt;a href="https://www.chartjs.org/docs/latest/getting-started/integration.html" rel="noopener noreferrer"&gt;documentation&lt;/a&gt; for the elements. The ones placed in the code above are for a line chart.&lt;/p&gt;

&lt;p&gt;Next, we proceed to fetching the data required to create the chart.&lt;/p&gt;

&lt;p&gt;We shall create a spinner to be shown while data fetching process takes place.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  if (!chartData || !chartData.prices) {
    return (
      &amp;lt;div className="flex items-center justify-center h-screen"&amp;gt;
        &amp;lt;div className="animate-spin rounded-full border-4 border-solid border-current border-r-transparent h-12 w-12"&amp;gt;&amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we shall have the logic to create the data structure that Chart.js will use to display the chart along with the properties such as the label, border color, border width, and point radius.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const { prices } = chartData;

  const data = {
    labels: prices.map((entry: any) =&amp;gt; new Date(entry[0]).toLocaleDateString()),
    datasets: [
      {
        label: "Price (USD)",
        data: prices.map((entry: any) =&amp;gt; entry[1].toFixed(2)),
        borderColor: "orange",
        borderWidth: 2,
        pointRadius: 4,
      },
    ],
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we render the line chart by passing in the data attribute in the &lt;code&gt;Line&lt;/code&gt; component from react-chartjs-2.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Line data={data} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Market Chart component will be as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  Tooltip,
  PointElement,
  LineElement,
} from "chart.js";
import { useEffect, useState } from "react";
import { Line } from "react-chartjs-2";

// Register ChartJS components using ChartJS.register
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Tooltip
);

interface LineProps {
  id: string;
}

const MarketChart: React.FC&amp;lt;LineProps&amp;gt; = ({ id }) =&amp;gt; {
  const [chartData, setChartData] = useState&amp;lt;any&amp;gt;(null);

  useEffect(() =&amp;gt; {
    const fetchData = async () =&amp;gt; {
      try {
        const response = await fetch(
          `https://api.coingecko.com/api/v3/coins/${id}/market_chart?vs_currency=usd&amp;amp;days=30&amp;amp;precision=2&amp;amp;interval=daily`
        );
        const data = await response.json();
        console.log("chartData:", data);
        setChartData(data);
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, [id]);

  if (!chartData || !chartData.prices) {
    return (
      &amp;lt;div className="flex items-center justify-center h-screen"&amp;gt;
        &amp;lt;div className="animate-spin rounded-full border-4 border-solid border-current border-r-transparent h-12 w-12"&amp;gt;&amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
  const { prices } = chartData;

  const data = {
    labels: prices.map((entry: any) =&amp;gt; new Date(entry[0]).toLocaleDateString()),
    datasets: [
      {
        label: "Price (USD)",
        data: prices.map((entry: any) =&amp;gt; entry[1].toFixed(2)),
        borderColor: "orange",
        borderWidth: 2,
        pointRadius: 4,
      },
    ],
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Line data={data} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
export default MarketChart;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Coin Details Component
&lt;/h3&gt;

&lt;p&gt;We shall proceed to plug the Market Chart component we created above to the Coin Details component which will render the respective charts for the coin selected. &lt;/p&gt;

&lt;p&gt;We create a div below the last element of the page and add the Market Chart component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        &amp;lt;div className="py-5"&amp;gt;
         &amp;lt;MarketChart id={details.id}/&amp;gt;
        &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then pass the &lt;code&gt;id&lt;/code&gt; of the current coin to allow for dynamic fetching of the market chart.&lt;/p&gt;

&lt;p&gt;The whole component will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { CoinDetails } from "@/types/coinDetails";
import Image from "next/image";
import alt from "@/assets/alt coin.jpg";
import MarketChart from "./MarketChart";

export async function CoinPage({ promise }: { promise: Promise&amp;lt;CoinDetails&amp;gt; }) {
  const details = await promise;

  const content = (
    &amp;lt;div className="p-5 text-gray-700" key={details.id}&amp;gt;
      &amp;lt;div className="flex flex-col justify-center"&amp;gt;
        &amp;lt;p className="py-1 px-2 w-24 bg-orange-500 text-white rounded-lg inline-block"&amp;gt;
          Rank #{details.market_cap_rank.toLocaleString()}
        &amp;lt;/p&amp;gt;
        &amp;lt;div className="flex items-center flex-wrap"&amp;gt;
          &amp;lt;Image
            src={details.image.small || alt}
            alt="coin image"
            width={30}
            height={30}
            className="mr-2"
          /&amp;gt;
          &amp;lt;h2 className="py-2 text-2xl text-black font-bold"&amp;gt;
            {details.name}
            &amp;lt;span className="px-2 text-base font-light text-neutral-400"&amp;gt;
              {details.symbol}
            &amp;lt;/span&amp;gt;
          &amp;lt;/h2&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;p className="py-3 text-xl text-black font-bold"&amp;gt;
          ${details.market_data.current_price.usd.toLocaleString()}
        &amp;lt;/p&amp;gt;
        &amp;lt;div className="grid grid-cols-1 sm:grid-cols-2 gap-4"&amp;gt;
          &amp;lt;ul className="py-1"&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;Market Cap:&amp;lt;/span&amp;gt; $
              {details.market_data.market_cap.usd.toLocaleString()}
            &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;
                Circulating Supply:
              &amp;lt;/span&amp;gt;{" "}
              ${details.market_data.circulating_supply.toLocaleString()}
            &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;
                Fully Diluted Valuation:
              &amp;lt;/span&amp;gt;{" "}
              $
              {details.market_data.fully_diluted_valuation.usd.toLocaleString()}
            &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;
                Market Cap Change (24h):
              &amp;lt;/span&amp;gt;{" "}
              {details.market_data.market_cap_change_percentage_24h.toFixed(1)}%
            &amp;lt;/li&amp;gt;
          &amp;lt;/ul&amp;gt;
          &amp;lt;ul className="py-1"&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;Maximum Supply:&amp;lt;/span&amp;gt; $
              {details.market_data.max_supply?.toLocaleString() || "N/A"}
            &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;
                Price Change % (24h):
              &amp;lt;/span&amp;gt;{" "}
              {details.market_data.price_change_percentage_24h.toFixed(1)}%
            &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;Total Supply:&amp;lt;/span&amp;gt; $
              {details.market_data.total_supply.toLocaleString()}
            &amp;lt;/li&amp;gt;
            &amp;lt;li&amp;gt;
              &amp;lt;span className="font-semibold py-2 mr-2"&amp;gt;Total Volume:&amp;lt;/span&amp;gt; $
              {details.market_data.total_volume.usd.toLocaleString()}
            &amp;lt;/li&amp;gt;
          &amp;lt;/ul&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div className="py-3"&amp;gt;
          &amp;lt;h3 className="text-xl font-bold "&amp;gt;Information&amp;lt;/h3&amp;gt;
          &amp;lt;ul&amp;gt;

            &amp;lt;li className="py-1"&amp;gt;
              &amp;lt;span className=" mr-2"&amp;gt;
                &amp;lt;a
                  href={details.links.homepage[0]}
                  className="hover:underline"
                  target="_blank"
                  rel="noopener noreferrer"
                &amp;gt;
                  Website: {details.name}.org
                &amp;lt;/a&amp;gt;
              &amp;lt;/span&amp;gt;{" "}
            &amp;lt;/li&amp;gt;
          &amp;lt;/ul&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div className="py-5"&amp;gt;
         &amp;lt;MarketChart id={details.id}/&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );

  return content;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check out the live demo and see the charts in action &lt;a href="https://krypto-app-silk.vercel.app/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The project is available &lt;a href="https://github.com/andisiambuku/Krypto-App" rel="noopener noreferrer"&gt;here&lt;/a&gt;. If you wish to contribute, feel free to create a pull request. &lt;br&gt;
To overcome some challenges such as rate limiting and if you wish to use more features of the Coin Gecko API, use my code CGANDISI500 for $500 of on your API subscription. Sign up &lt;a href="https://www.coingecko.com/en/api/pricing" rel="noopener noreferrer"&gt;here&lt;/a&gt; to redeem the discount.&lt;/p&gt;

&lt;p&gt;Thank you for reading! Until next time, may the code be with you.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Creating a Cryptocurrency App with Next JS and Coin Gecko API</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Thu, 02 Nov 2023 16:07:28 +0000</pubDate>
      <link>https://dev.to/andisiambuku/creating-a-cryptocurrency-app-with-next-js-and-coin-gecko-api-b7h</link>
      <guid>https://dev.to/andisiambuku/creating-a-cryptocurrency-app-with-next-js-and-coin-gecko-api-b7h</guid>
      <description>&lt;p&gt;Cryptocurrency has rapidly changed the financial systems across the globe and its adoption along with blockchain has skyrocketed.&lt;br&gt;
In this tutorial, we shall create a cryptocurrency website using Next JS and the Coin gecko API which will display real-time cryptocurrency coin information. &lt;/p&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;In this tutorial we shall use the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node JS installed in your machine.&lt;/li&gt;
&lt;li&gt;Next 13&lt;/li&gt;
&lt;li&gt;The documentation for the Coin Gecko API is available here. Be sure to refer to the documentation whenever we use an endpoint.&lt;/li&gt;
&lt;li&gt;Tailwind CSS for styling our app.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Setting up Next JS app
&lt;/h2&gt;

&lt;p&gt;We shall use the automatic installation method to set up the app. It is a quick and simple method. &lt;br&gt;
We begin by typing the following command in the terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-next-app@latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Answer the prompts that follow appropriately.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;What is your project named? my-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like to use `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to customize the default import alias? No / Yes
What import alias would you like configured? @/*
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the app with the following command to ensure set up was successful.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm run dev&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;We shall use SWR to fetch and cache data in our application. &lt;strong&gt;SWR&lt;/strong&gt; (Stale-while-revalidate) is a library used to fetch data similar to fetch API but with more features such as caching. To install it type the following command in the terminal.&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install swr&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Building the Next JS App
&lt;/h2&gt;

&lt;p&gt;Before we begin building the app, we shall create a function responsible for making HTTP requests and handling responses. This function is used in conjunction with useSWR for data fetching.&lt;br&gt;
In the root of your app, create a folder called lib and create a file called fetcher.tsx and have the following code.&lt;br&gt;
&lt;br&gt;
 &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetcher (url:string){
    const res = await fetch(url)
    if(!res.ok){
      throw new Error('Network response failed')
    }
    return res.json()
}
export default fetcher
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;We shall begin by creating the layout components of our app which are the navbar and footer. &lt;/p&gt;
&lt;h2&gt;
  
  
  Footer
&lt;/h2&gt;

&lt;p&gt;The footer shall contain attribution to the Coin Gecko API as we shall use the free plan for the API. &lt;/p&gt;

&lt;p&gt;Create a folder at the root of your app called components. This is because Next 13 has app routing functionality meaning that any folder within the app folder is treated as a route. For the sake of clarity, we can create the components folder at the root and import the components in the required files as per need.&lt;/p&gt;

&lt;p&gt;Create a footer.tsx file and type in this code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function Footer(){
return(
    &amp;lt;footer
        className="bg-neutral-100 text-center lg:text-left"&amp;gt;
        &amp;lt;div className="p-4 text-center text-black"&amp;gt;
            Powered by
        &amp;lt;a
        className="text-black"
        href="https://www.coingecko.com/"
        &amp;gt; CoinGecko API&amp;lt;/a&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/footer&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw8y4cb3se1n15pwvrbz3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw8y4cb3se1n15pwvrbz3.png" alt="Footer" width="800" height="209"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This code consists of a function called Footer() that creates a footer with the "Powered by CoinGecko API" and a link to the CoinGecko API for attribution purposes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Navbar 
&lt;/h2&gt;

&lt;p&gt;In the components folder, create a file called navbar.tsx and type in this code.&lt;br&gt;
&lt;br&gt;
 &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import SearchBar from "./SearchBar";

export default function Navbar(){
    return(
      &amp;lt;nav
  className="relative flex w-full flex-wrap items-center justify-between bg-[#FBFBFB] py-2 text-neutral-500 shadow-lg hover:text-[#f59e0b] focus:text-[#f59e0b]  lg:py-4"&amp;gt;
  &amp;lt;div className="flex w-full flex-wrap items-center justify-between px-3"&amp;gt;
    &amp;lt;a
      className="ml-2 text-2xl text-[#f59e0b] "
      href="#"
      &amp;gt;KRYPTO APP&amp;lt;/a&amp;gt;
    &amp;lt;SearchBar/&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;/nav&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This code consists of a function called Navbar() that creates a navbar at the top of the screen with the name of the app to the left and a search bar on the right which shall be used to search for a coin.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdyqzh3a3y6d0d962vg7y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdyqzh3a3y6d0d962vg7y.png" alt="Navbar" width="800" height="60"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Search bar
&lt;/h2&gt;

&lt;p&gt;Since we are using Typescript, we shall have the types of the search feature in a separate folder. In the root directory create a folder called types.&lt;br&gt;
Search Types&lt;br&gt;
Create a file called coinMarkets.d.ts and add the following code. The types are from the Coin Gecko API /search endpoint response. Be sure to check out the documentation here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export type CoinSearch = {

    "id": string,
    "name": string,
    "api_symbol":string,
    "symbol": string,
    "market_cap_rank": number,
    "thumb": string,
    "large": string
}
export type SearchResponse = {
    categories: [],
    coins: CoinSearch[],
    ico:[],
    nfts:[]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;CoinSearch is a type that describes the structure of an object representing a coin in a search context with properties that contain coin information. SearchResponse is a type that represents a response structure from a search operation with categories, coins, ico and nft properties. These are from the search endpoint. &lt;br&gt;
The types are from the Coin Gecko API endpoint response. Be sure to check out the documentation here.&lt;/p&gt;
&lt;h2&gt;
  
  
  Search bar component
&lt;/h2&gt;

&lt;p&gt;In the components folder, create a file called searchbar.tsx and type in this code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client"

import { CoinSearch, SearchResponse } from '@/types/coinMarkets';
import React, { useState } from 'react';
import Image from 'next/image'
import alt from '@/assets/alt coin.jpg'
import Link from 'next/link';

export default function SearchBar() {
  const [query, setQuery] = useState('');
  const [searchResults, setSearchResults] = useState&amp;lt;SearchResponse | undefined&amp;gt;();

  const handleInputChange = (e: React.ChangeEvent&amp;lt;HTMLInputElement&amp;gt;) =&amp;gt; {
    setQuery(e.target.value);
    if (e.target.value.trim() === '') {
      setSearchResults(undefined);
    }
  };

  const handleSearchClick = async () =&amp;gt; {
    try {
      if (query.trim() !== '') {
        const apiUrl = `https://api.coingecko.com/api/v3/search?query=${encodeURIComponent(query)}`;
        const response = await fetch(apiUrl);

        if (!response.ok) {
          throw new Error(`Network response was not ok (status: ${response.status})`);
        }

        // Check if the response is valid JSON
        const contentType = response.headers.get('content-type');
        if (contentType &amp;amp;&amp;amp; contentType.includes('application/json')) {
          const searchData: SearchResponse = await response.json();
          setSearchResults(searchData);
        } else {
          throw new Error('Response is not valid JSON');
        }
      }
    } catch (error) {
      console.error('Error during search:', error);
      // Handle errors, e.g., display an error message to the user
    }
  };

  const handleResultItemClick = () =&amp;gt;{
    setSearchResults(undefined)
  }

  return (
    &amp;lt;div className="ml-5 flex w-[30%] items-center justify-between relative"&amp;gt;
      &amp;lt;input
        type="search"
        className="relative m-0 block w-[1px] min-w-0 flex-auto  border border-solid border-[#f59e0b] bg-transparent bg-clip-padding px-3 py-[0.25rem] font-normal leading-[1.6]  outline-none transition duration-200 ease-in-out"
        placeholder="Search"
        aria-label="Search"
        aria-describedby="button-addon2"
        value={query}
        onChange={handleInputChange}
      /&amp;gt;

      &amp;lt;button
        type="button"
        aria-label="Search"
        className="input-group-text flex items-center  px-3 py-2 text-center font-normal text-white bg-[#f59e0b]"
        id="basic-addon2"
        onClick={handleSearchClick}
      &amp;gt;
        &amp;lt;svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 20 20"
          fill="currentColor"
          className="h-5 w-5"
        &amp;gt;
          &amp;lt;path
            fillRule="evenodd"
            d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z"
            clipRule="evenodd"
          /&amp;gt;
        &amp;lt;/svg&amp;gt;
      &amp;lt;/button&amp;gt;
      {/* Display search results */}
      {searchResults?.coins != null &amp;amp;&amp;amp; searchResults?.coins.length&amp;gt; 0 &amp;amp;&amp;amp; (
        &amp;lt;div style={{position:'absolute', top: '45px',height:'250px',overflow:'scroll',background:'white',zIndex:2, width:'365px'}} className=""&amp;gt;
          &amp;lt;ul&amp;gt;
            {searchResults?.coins.map((result: CoinSearch) =&amp;gt; (
              &amp;lt;li key={result.id} onClick={handleResultItemClick} className="flex items-center p-3"&amp;gt;
                &amp;lt;div className="p-1"&amp;gt;&amp;lt;Image src={result.thumb || alt} alt={"coin image"} width={30} height={30}/&amp;gt;&amp;lt;/div&amp;gt;
                &amp;lt;div className="p-1 text-neutral-500"&amp;gt;&amp;lt;Link href={`/coins/${result.id}`}&amp;gt;{result.name}&amp;lt;/Link&amp;gt;&amp;lt;/div&amp;gt;
                &amp;lt;div className="ml-auto text-neutral-500 text-xs"&amp;gt;#{result.market_cap_rank}&amp;lt;/div&amp;gt;
               &amp;lt;/li&amp;gt;
            ))}
          &amp;lt;/ul&amp;gt;
        &amp;lt;/div&amp;gt;
       )}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code defines a component, Search Bar, which serves as a search input field for querying the Coin Gecko API and displaying search results based on user input.&lt;br&gt;
The component maintains state using the useState hook for query (user input for search) and searchResults (results fetched from the API).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;handleInputChange function updates the query state based on the input changes and resets searchResults if the input is empty.&lt;/li&gt;
&lt;li&gt;handleSearchClick function triggers an API call to fetch data based on the input query. It updates searchResults with the fetched data if the response is successful and in JSON format.&lt;/li&gt;
&lt;li&gt;handleResultItemClick function clears the searchResults to hide the search result list upon clicking an item.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Import the Search bar component to the Navbar.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd2hjka8c6bavhtd3b3hk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd2hjka8c6bavhtd3b3hk.png" alt="Navbar" width="800" height="279"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Root Layout 
&lt;/h2&gt;

&lt;p&gt;In the root layout we define the layout structure for web pages in the application, including global font settings, metadata configuration, and the inclusion of common components like Navbar and Footer in a consistent manner for all pages. Open the layout.tsx file and have this code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import './globals.css'
import type { Metadata } from 'next'
import { Montserrat } from 'next/font/google'
import Navbar from '@/components/Navbar'
import Footer from '@/components/Footer'

const montserrat = Montserrat({
  subsets: ['latin'],
  weight: '400'
})

export const metadata: Metadata = {
  title: 'Krypto App',
  description: 'A cryptocurrency market analysis app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    &amp;lt;html lang="en"&amp;gt;

      &amp;lt;body className={montserrat.className}&amp;gt;
        &amp;lt;Navbar/&amp;gt;
        {children}
        &amp;lt;Footer/&amp;gt;
        &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Font Configuration:&lt;/strong&gt;&lt;br&gt;
const montserrat = Montserrat({ subsets: ['latin'], weight: '400' }): Configures the Montserrat font by specifying its subsets (e.g., Latin characters) and weight (e.g., '400' for regular).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Metadata:&lt;/strong&gt;&lt;br&gt;
export const metadata: Metadata = { ... }: Defines metadata properties for the page, such as title and description. These properties are used for search engine optimization (SEO) and other metadata-related purposes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RootLayout Component:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;export default function RootLayout({ children }: { children: React.ReactNode }) { ... }&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
: Defines the RootLayout component responsible for creating a layout structure that wraps around the content (children) of individual pages.&lt;br&gt;
It uses an  structure to set the language to English (lang="en").&lt;br&gt;
The &lt;/p&gt; element is assigned a class based on the configured Montserrat font using montserrat.className.&lt;br&gt;
Inside the body, it includes the Navbar component, the children (actual content of the page), and the Footer component.
&lt;h2&gt;
  
  
  Homepage
&lt;/h2&gt;

&lt;p&gt;We shall move to creating the home page which is what our users will see when they land on our page.&lt;br&gt;
We begin by creating the Coin market component which will contain the coins and real-time information about them in a tabular format.&lt;br&gt;
Coin market types&lt;br&gt;
In the file called coinMarkets.d.ts and add the following code. The types are from the Coin Gecko API /coins/list endpoint response. Be sure to check out the documentation &lt;a href="https://www.coingecko.com/en/api/documentation" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export type CoinMarkets ={
    'id': string,
    "symbol": string,
    "name": string,
    "image": string,
    "current_price": number,
    "market_cap": number,
    "market_cap_rank": number,
    "fully_diluted_valuation": number,
    "total_volume": number,
    "high_24h": number,
    "low_24h": number,
    "price_change_24h": number,
    "price_change_percentage_24h": number,
    "market_cap_change_24h": number,
    "market_cap_change_percentage_24h": number,
    "circulating_supply": number,
    "total_supply": number,
    "max_supply": number,
    "ath": number,
    "ath_change_percentage": number,
    "ath_date": string,
    "atl": number,
    "atl_change_percentage": number,
    "atl_date": string,
    "roi": null,
    "last_updated": string
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Coin markets component
&lt;/h2&gt;

&lt;p&gt;To create the component, create a coinmarkets.tsx file in the components folder and have the following code in the file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Image from 'next/image'
import Link from 'next/link'
import alt from '@/assets/alt coin.jpg'
import { CoinMarkets } from '@/types/coinMarkets'

interface Coins {
    id: string,
    symbol: string,
    name: string,
    image: string,
    current_price: number,
    market_cap_rank: number,
    market_cap: number,
    total_volume: number,
    price_change_percentage_24h: number,

}

interface Props {
    coin: CoinMarkets[]
}

export default function Coins({ coin }: Props){
    return(
        &amp;lt;div className='p-6 flex flex-col overflow-x-auto'&amp;gt;
            &amp;lt;div className="sm:-mx-6 lg:-mx-8"&amp;gt;
            &amp;lt;div className="inline-block min-w-full py-2 sm:px-6 lg:px-8"&amp;gt;
            &amp;lt;div className="overflow-x-auto"&amp;gt;&amp;lt;/div&amp;gt;
                &amp;lt;table className="min-w-full text-left text-sm font-light"&amp;gt;
                    &amp;lt;thead className="border-b font-medium dark:border-neutral-200"&amp;gt;
                        &amp;lt;tr&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;#&amp;lt;/th&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;Coin&amp;lt;/th&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;Price&amp;lt;/th&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;Market Cap&amp;lt;/th&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;Total Volume&amp;lt;/th&amp;gt;
                            &amp;lt;th className="px-6 py-4"&amp;gt;24h &amp;lt;/th&amp;gt;
                        &amp;lt;/tr&amp;gt;
                    &amp;lt;/thead&amp;gt;
                    &amp;lt;tbody&amp;gt;
                        {coin.map((coin) =&amp;gt;(
                            &amp;lt;tr className="border-b dark:border-neutral-200" key={coin.id} &amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;{coin.market_cap_rank}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;&amp;lt;Image src={coin.image || alt} alt={"coin image"} width={30} height={30}/&amp;gt;&amp;lt;/td&amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;&amp;lt;Link href={`/coins/${coin.id}`}&amp;gt;{coin.name}{' '}
                                &amp;lt;span className="text-neutral-500"&amp;gt;{coin.symbol}&amp;lt;/span&amp;gt;&amp;lt;/Link&amp;gt;&amp;lt;/td&amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;$ {coin.current_price.toLocaleString()}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;$ {coin.market_cap.toLocaleString()}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;$ {coin.total_volume.toLocaleString()}&amp;lt;/td&amp;gt;
                                &amp;lt;td className="whitespace-nowrap px-6 py-4"&amp;gt;{(coin.price_change_percentage_24h).toFixed(1)}%&amp;lt;/td&amp;gt;
                            &amp;lt;/tr&amp;gt;
                        ))}
                    &amp;lt;/tbody&amp;gt;
                &amp;lt;/table&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Component Structure:&lt;/strong&gt;&lt;br&gt;
The component (Coins) receives props as an array of coin objects, each adhering to the structure defined by the CoinMarkets interface.&lt;br&gt;
It renders a table containing information about the coins.&lt;br&gt;
For each coin in the coin array, it generates a table row (&lt;/p&gt;
&lt;tr&gt;) containing specific details in different table data cells (&lt;td&gt;).

&lt;p&gt;&lt;strong&gt;Table Structure:&lt;/strong&gt;&lt;br&gt;
The table has a header row (&lt;thead&gt;) and a body section (&lt;/thead&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tbody&gt;).&lt;br&gt;
The header row contains table headers for various details like rank, coin image, name, price, market cap, total volume, and 24-hour price change percentage.&lt;br&gt;
The body section iterates over each coin object from the props and generates a table row for each coin.

&lt;p&gt;&lt;strong&gt;Data Rendering:&lt;/strong&gt;&lt;br&gt;
Each table row displays specific information about a particular coin.&lt;br&gt;
Information like market cap rank, coin image, name (linked to the detailed coin page), price, market cap, total volume, and 24-hour price change percentage are shown in individual columns within the table row.&lt;br&gt;
The coin's image is displayed using the Image component from Next.js, with a default image provided in case the specific coin image is unavailable.&lt;br&gt;
The coin's name is rendered as a link using the Link component, allowing users to navigate to a detailed page about the coin.&lt;br&gt;
Various coin data such as market cap, price, and volumes are displayed, with appropriate formatting (e.g., numbers are formatted using toLocaleString() for better readability).&lt;/p&gt;
&lt;h3&gt;
  
  
  UseData Hook
&lt;/h3&gt;

&lt;p&gt;To fetch the data, we need for the homepage we shall create a hook called useData. &lt;br&gt;
In the root of your app, create a folder called hooks and create a file called useData.tsx and have the following code.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useSWR from "swr"
import fetcher from '@/lib/fetcher'

const apiUrl = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&amp;amp;order=market_cap_desc&amp;amp;per_page=100&amp;amp;page=1&amp;amp;sparkline=false&amp;amp;locale=en'
export const useData = () =&amp;gt;{
    const { data, error,isLoading } = useSWR(apiUrl, fetcher)

    return{
        data, 
        error,
        isLoading
    }
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;code&gt;export const useData = () =&amp;gt; { ... }&lt;/code&gt;: Defines a custom hook called useData responsible for fetching data from the specified API endpoint using useSWR.&lt;br&gt;
&lt;code&gt;const { data, error, isLoading } = useSWR(apiUrl, fetcher)&lt;/code&gt;: Uses the useSWR hook to fetch data from the specified apiUrl using the provided fetcher function. This hook manages the data, any potential errors, and a loading state.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;data: Contains the fetched data from the API if the request is successful.&lt;/li&gt;
&lt;li&gt;error: Represents any potential error that occurs during the data fetching process.&lt;/li&gt;
&lt;li&gt;isLoading: Indicates whether the data is currently being loaded, i.e., a loading state while the request is in progress.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;return { data, error, isLoading }&lt;/code&gt;: The useData hook returns an object containing the fetched data, any error encountered during the fetch, and the loading state isLoading.&lt;/p&gt;

&lt;p&gt;At the page.tsx file in the app folder have the following code.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client"
import Coins from "@/components/CoinMarkets"
import {useData} from '@/hooks/useData'

export default function Home() {
  const { data, error, isLoading } = useData()
  if(error){ 
    return ( 
    &amp;lt;div className="text-center h-screen text-2xl p-10 text-[#f59e0b]"&amp;gt;Oops! &amp;lt;br&amp;gt;&amp;lt;/br&amp;gt; Error loading data&amp;lt;/div&amp;gt;
    ) 
  }
  if(isLoading){ 
  return (  
  &amp;lt;div className="p-10 flex flex-col overflow-x-auto"&amp;gt;
  &amp;lt;div className="sm:-mx-6 lg:-mx-8"&amp;gt;
    &amp;lt;div className="inline-block min-w-full py-2 sm:px-6 lg:px-8"&amp;gt;
      &amp;lt;div className="overflow-x-auto"&amp;gt;
        &amp;lt;table className="min-w-full text-left text-sm font-light animate-pulse"&amp;gt;
          {/* Skeleton loading rows */}
          &amp;lt;thead className="border-b font-medium dark:border-neutral-200 animate-pulse"&amp;gt;
            &amp;lt;tr&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
              &amp;lt;th className="px-6 py-4"&amp;gt;&amp;lt;/th&amp;gt;
            &amp;lt;/tr&amp;gt;
          &amp;lt;/thead&amp;gt;
          &amp;lt;tbody&amp;gt;
            {/* Render skeleton loading rows */}
            {[1, 2, 3, 4, 5,6,7,8,9,10,11].map((_, index) =&amp;gt; (
              &amp;lt;tr
                className="border-b dark:border-neutral-200 animate-pulse "
                key={index}
              &amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-6 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-6 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-1 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-6 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-6 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-6 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
                &amp;lt;td className="whitespace-nowrap text-neutral-300 px-6 py-4"&amp;gt;Loading&amp;lt;/td&amp;gt;
              &amp;lt;/tr&amp;gt;
            ))}
          &amp;lt;/tbody&amp;gt;
        &amp;lt;/table&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;) }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Coins coin={data} /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;The Home component in this code is responsible for managing the loading, error, and success states of cryptocurrency market data.&lt;br&gt;
It uses conditional rendering to handle different states (error, loading, and successful data fetch) and provides visual feedback to the user accordingly.&lt;br&gt;
During the loading phase, it displays a loading skeleton to maintain the layout structure and give the user a visual indication that content is being fetched.&lt;br&gt;
When the data is successfully loaded, it renders the Coins component to display the fetched cryptocurrency market information in a tabular format.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp8q6cyr9ibag1xlvld2c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp8q6cyr9ibag1xlvld2c.png" alt="Homepage" width="800" height="398"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Coin Details Page
&lt;/h2&gt;

&lt;p&gt;We shall move to creating the coin details page which is what our users will see when they click on a single coin or search for a coin.&lt;br&gt;
We begin by creating the Coin details component.&lt;br&gt;
Coin details type&lt;br&gt;
In the file called coinDetails.d.ts and add the following code. The types are from the Coin Gecko API endpoint response /coins/{id}. Be sure to check out the documentation &lt;a href="https://www.coingecko.com/api/documentation" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export type CoinDetails = {
    "id": string,
    "symbol": string,
    "name": string,
    "asset_platform_id": null,
    "platforms": {
      "": string
    },
    "detail_platforms": {
      "": {
        "decimal_place": null,
        "contract_address": string
      }
    },
    "block_time_in_minutes": number,
    "hashing_algorithm": string,
    "categories": [
        string,
        string,
        string
    ],
    "preview_listing": boolean,
    "public_notice": null,
    "additional_notices": [],
    "description": {
      "en": string
    },
    "links": {
      "homepage": [
        string,
        string,
        string
      ],
      "blockchain_site": [
        string,
        string,
        string,
        string,
        string,
        "",
        "",
        "",
        "",
        ""
      ],
      "official_forum_url": [
        string,
        "",
        ""
      ],

      "twitter_screen_name": string,
      "facebook_username": string,
      "bitcointalk_thread_identifier": null,
      "telegram_channel_identifier": string,
      "subreddit_url": string,
      "repos_url": {
        "github": [
            string,
            string
        ],
        "bitbucket": []
      }
    },
    "image": {
      "thumb": string,
      "small": string,
      "large": string
    },
    "country_origin": string,
    "genesis_date": string,
    "sentiment_votes_up_percentage": number,
    "sentiment_votes_down_percentage": number,
    "watchlist_portfolio_users": number,
    "market_cap_rank": number,
    "coingecko_rank": number,
    "coingecko_score": number,
    "developer_score": number,
    "community_score": number,
    "liquidity_score": number,
    "public_interest_score": number,
    "market_data": {
      "current_price": {
        "usd": number,
      },
      "total_value_locked": null,
      "mcap_to_tvl_ratio": null,
      "fdv_to_tvl_ratio": null,
      "roi": null,
      "market_cap": {
        "usd": number,
      },
      "market_cap_rank": number,
      "fully_diluted_valuation": {
        "usd": number,
      },
      "market_cap_fdv_ratio": number,
      "total_volume": {
        "usd": number,
      },
      "price_change_24h": number,
      "price_change_percentage_24h": number,
      "price_change_percentage_7d": number,
      "price_change_percentage_14d": number,
      "price_change_percentage_30d": number,
      "price_change_percentage_60d": number,
      "price_change_percentage_200d": number,
      "price_change_percentage_1y": number,
      "market_cap_change_24h": number,
      "market_cap_change_percentage_24h": number,
      "total_supply": number,
      "max_supply": number,
      "circulating_supply": number,
      "sparkline_7d": {
        "price": number []
      },
      "last_updated": string
    },
    "public_interest_stats": {
      "alexa_rank":number,
      "bing_matches": null
    },
    "status_updates": [],
    "last_updated": string
  }
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;useDetails hook&lt;/strong&gt;&lt;br&gt;
To fetch the data, we need for the coin details page we shall create a hook called useDetails.&lt;br&gt;
In the root of your app, create a folder called hooks and create a file called useDetails.tsx and have the following code.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import useSWR from "swr"
import fetcher from '@/lib/fetcher'

export const useCoinDetails = (id: string) =&amp;gt;{

    const apiUrl = `https://api.coingecko.com/api/v3/coins/${id}?localization=false&amp;amp;tickers=false&amp;amp;market_data=true&amp;amp;community_data=false&amp;amp;developer_data=false&amp;amp;sparkline=true`

    const {  isLoading, error, data  } = useSWR(apiUrl, fetcher)

    return{
        isLoading,
        error,
        data,
    }
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;code&gt;export const useCoinDetails = (id: string) =&amp;gt; { ... }&lt;/code&gt;: Defines the useCoinDetails hook, which receives an id parameter (the cryptocurrency's identifier) to fetch details for the specified cryptocurrency.&lt;br&gt;
It reassigns the apiUrl variable, dynamically constructing the API endpoint by including the provided id in the URL to fetch data for a specific cryptocurrency.&lt;/p&gt;

&lt;p&gt;It uses useSWR to fetch data from the dynamically generated apiUrl using the provided fetcher function.&lt;br&gt;
Manages the loading state (isLoading), any potential errors (error), and the fetched data (data).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;return { isLoading, error, data }&lt;/code&gt;: The useCoinDetails hook returns an object containing the loading state, any errors encountered during fetching, and the fetched data for the specified cryptocurrency.&lt;/p&gt;
&lt;h2&gt;
  
  
  Coin details component
&lt;/h2&gt;

&lt;p&gt;Next in the components folder, create a coindetails.tsx file and have the following code.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { CoinDetails} from "@/types/coinDetails"
import Image from 'next/image'
import alt from '@/assets/alt coin.jpg'

export async function CoinPage({ promise }: { promise: Promise&amp;lt;CoinDetails&amp;gt; }) {
    const details = await promise

    const content = (
        &amp;lt;div className=" p-8 text-gray-700" key={details.id}&amp;gt;
          &amp;lt;div className="flex flex-col lg:flex-row justify-between"&amp;gt;
            &amp;lt;div className="mb-4 lg:mb-0 basis-2/3"&amp;gt;
              &amp;lt;p className="py-1 px-2 bg-orange-500 text-white rounded-lg inline-block"&amp;gt;Rank # {details.market_cap_rank.toLocaleString()}&amp;lt;/p&amp;gt;
              &amp;lt;div className="flex items-center"&amp;gt;
              &amp;lt;Image src={details.image.small || alt} alt="coin image" width={30} height={30} className="mr-2"&amp;gt;&amp;lt;/Image&amp;gt;
              &amp;lt;h2 className="py-2 text-2xl text-black font-bold"&amp;gt;{details.name}&amp;lt;span className=" px-2 text-base font-light text-neutral-400"&amp;gt;{details.symbol}&amp;lt;/span&amp;gt;&amp;lt;/h2&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;p className="py-3 text-xl text-black font-bold"&amp;gt;${details.market_data.current_price.usd.toLocaleString()}&amp;lt;/p&amp;gt;
              &amp;lt;div className="grid grid-cols-1 sm:grid-cols-2 gap-4"&amp;gt;
                &amp;lt;ul className="py-1"&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Market Cap:&amp;lt;/span&amp;gt; ${details.market_data.market_cap.usd.toLocaleString()}&amp;lt;/li&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Circulating Supply:&amp;lt;/span&amp;gt; ${details.market_data.circulating_supply.toLocaleString()}&amp;lt;/li&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Fully Diluted Valuation:&amp;lt;/span&amp;gt; ${details.market_data.fully_diluted_valuation.usd.toLocaleString()}&amp;lt;/li&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Market Cap Change (24h):&amp;lt;/span&amp;gt; {details.market_data.market_cap_change_percentage_24h.toFixed(1)}%&amp;lt;/li&amp;gt;
                &amp;lt;/ul&amp;gt;
                &amp;lt;ul className="py-1"&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Maximum Supply:&amp;lt;/span&amp;gt; ${details.market_data.max_supply?.toLocaleString() || 'N/A'}&amp;lt;/li&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Price Change Percentage (24h):&amp;lt;/span&amp;gt; {details.market_data.price_change_percentage_24h.toFixed(1)}%&amp;lt;/li&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Total Supply:&amp;lt;/span&amp;gt; ${details.market_data.total_supply.toLocaleString()}&amp;lt;/li&amp;gt;
                  &amp;lt;li&amp;gt;&amp;lt;span className="font-semibold py-2 mr-5"&amp;gt;Total Volume:&amp;lt;/span&amp;gt; ${details.market_data.total_volume.usd.toLocaleString()}&amp;lt;/li&amp;gt;
                &amp;lt;/ul&amp;gt;
              &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;

            &amp;lt;div className="basis-1/3"&amp;gt;
              &amp;lt;h3 className="text-xl font-bold "&amp;gt;Information&amp;lt;/h3&amp;gt;
              &amp;lt;ul className="py-3"&amp;gt;
                &amp;lt;li className="py-1"&amp;gt;&amp;lt;span className="font-semibold mr-5"&amp;gt;Liquidity Score:&amp;lt;/span&amp;gt; {details.liquidity_score}%&amp;lt;/li&amp;gt;
                &amp;lt;li className="py-1"&amp;gt;&amp;lt;span className="font-semibold mr-5"&amp;gt;Community Score:&amp;lt;/span&amp;gt; {details.community_score}%&amp;lt;/li&amp;gt;
                &amp;lt;li className="py-1"&amp;gt;&amp;lt;span className="font-semibold mr-5"&amp;gt;&amp;lt;a href={details.links.homepage[0]} className=" hover:underline" target="_blank" rel="noopener noreferrer"&amp;gt;
                  Website: {details.name}.org &amp;lt;/a&amp;gt;&amp;lt;/span&amp;gt; &amp;lt;/li&amp;gt;
                &amp;lt;li className="py-1"&amp;gt;&amp;lt;span className="font-semibold mr-5"&amp;gt; Public Interest Score:&amp;lt;/span&amp;gt; {details.public_interest_score.toFixed(1)}%&amp;lt;/li&amp;gt;
              &amp;lt;/ul&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;div className="py-5 "&amp;gt;
            &amp;lt;h3 className="text-xl font-bold py-3"&amp;gt;Description&amp;lt;/h3&amp;gt;
            &amp;lt;p className=""&amp;gt;{details.description.en}&amp;lt;/p&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      );

      return content;

}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;The &lt;code&gt;CoinPage&lt;/code&gt; function is marked as async, signifying that it will use await to resolve the given promise.&lt;br&gt;
It takes an object as a parameter with a promise property of type &lt;code&gt;Promise&amp;lt;CoinDetails&amp;gt;&lt;/code&gt;. This promise resolves to fetch the details of a specific cryptocurrency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inside the function:&lt;/strong&gt;&lt;br&gt;
It awaits the resolution of the promise provided as the promise argument.&lt;br&gt;
After resolving the promise, it generates content to display the details of the specific cryptocurrency.&lt;br&gt;
The content is structured using HTML and Tailwind CSS classes for styling and layout.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Content Display: *&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The function creates a detailed display of various information about the cryptocurrency, organizing the content into different sections.&lt;/li&gt;
&lt;li&gt;It uses the resolved details object to access and display specific details, such as name, symbol, market data, scores, and descriptions.&lt;/li&gt;
&lt;li&gt;Utilizes conditional rendering to display specific information such as max_supply and website links, and provides 'N/A' in case some data is not available.&lt;/li&gt;
&lt;li&gt;The content is divided into sections, including market details, supply details, additional scores, and a description of the cryptocurrency.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Coins route&lt;/strong&gt;&lt;br&gt;
Next, we create the route to the coin details. We shall have a dynamic route for this, and we do so by creating a folder with the app folder called coins.&lt;br&gt;
The dynamic segment is created by wrapping a folder's name in square brackets, in the coins folder create a folder called &lt;code&gt;[id]&lt;/code&gt; and then have a page.tsx file to let Next now that this page shall be rendered.&lt;br&gt;
In the pages.tsx file have the following code.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'use client'
import { Suspense } from "react";
import { CoinPage } from "../../../components/CoinDetails";
import { useCoinDetails } from "@/hooks/useCoinDetails";


export default function Page({params}: { params: {id:string}}){
    const {data,error,isLoading} = useCoinDetails(params.id)
    return(
        &amp;lt;Suspense fallback={&amp;lt;div&amp;gt;Loading coin details...&amp;lt;/div&amp;gt;}&amp;gt;
            {isLoading ? (
                &amp;lt;div&amp;gt;Loading coin details..&amp;lt;/div&amp;gt;
            ):error ?(
                &amp;lt;div&amp;gt;Error loading coin details: {error.message}&amp;lt;/div&amp;gt;
            ): (
                &amp;lt;CoinPage promise={data}/&amp;gt;
            )} 

        &amp;lt;/Suspense&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;



&lt;ul&gt;
&lt;li&gt;The useCoinDetails hook is utilized to fetch the data for the specific cryptocurrency based on the provided id.&lt;/li&gt;
&lt;li&gt;The component returns JSX code that uses the Suspense component to handle the asynchronous data loading.&lt;/li&gt;
&lt;li&gt;Within the Suspense component, it conditionally renders different views based on the state of the data fetch (data, error, isLoading). It wraps the conditional rendering with a fallback defined as a loading message. This ensures that while the data is being fetched, a loading indicator is displayed to maintain a good user experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Conditional Rendering:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Loading State: If isLoading is true, it displays a simple loading message while waiting for the data to load.&lt;/li&gt;
&lt;li&gt;Error State: If an error occurs during the data fetch, it displays an error message showing the error details.&lt;/li&gt;
&lt;li&gt;Data Render: If there's no loading or error state (isLoading is false and there's no error), it renders the CoinPage component, passing the fetched data as a promise.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq15u7vtf23ngb44wyakp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq15u7vtf23ngb44wyakp.png" alt="Coin Details Page" width="800" height="407"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The project is available &lt;a href="https://github.com/andisiambuku/Krypto-App" rel="noopener noreferrer"&gt;here&lt;/a&gt;. If you wish to contribute, feel free to create a pull request. &lt;br&gt;
To overcome some challenges such as rate limiting and if you wish to use more features of the Coin Gecko API, use my code &lt;strong&gt;CGANDISI500&lt;/strong&gt; for $500 of on your API subscription. Sign up &lt;a href="https://www.coingecko.com/en/api/pricing" rel="noopener noreferrer"&gt;here&lt;/a&gt; to redeem the discount.&lt;br&gt;
Thank you for reading! Until next time, may the code be with you.&lt;/p&gt;


&lt;/tbody&gt;

</description>
      <category>coingecko</category>
      <category>nextjs</category>
      <category>cryptocurrency</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Working with GraphQL in Nest JS</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Mon, 04 Sep 2023 10:49:31 +0000</pubDate>
      <link>https://dev.to/andisiambuku/working-with-graphql-in-nest-js-137</link>
      <guid>https://dev.to/andisiambuku/working-with-graphql-in-nest-js-137</guid>
      <description>&lt;p&gt;&lt;strong&gt;Graph Query Language&lt;/strong&gt; or GraphQL is an API query language. &lt;/p&gt;

&lt;p&gt;It allows us to fetch precise data per request instead of fetching unneeded data and delivering it to us. GraphQL is an intuitive method of fetching data. &lt;/p&gt;

&lt;p&gt;An example scenario is when you are asked what your age is. The person asking only expects your age e.g. 44 years old. You don't begin by mentioning your birth date, where you were born, or even your parents. &lt;/p&gt;

&lt;p&gt;The precision in data fetching is the power of GraphQL.&lt;/p&gt;

&lt;p&gt;Let us go over a few common terms you will come across when working with GraphQL.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Schema&lt;/strong&gt;: defines the structure of the API. GraphQL has its type system for this and the language used to write the schema is called Schema Definition Language(SDL).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Types&lt;/strong&gt;: are the entities we would like to have in our application. For example, in a notes app, the &lt;strong&gt;note&lt;/strong&gt; will be a type. There are different types namely scalar, enum, union, object, and interface types.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Fields&lt;/strong&gt;: define the data of the types.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;type and field example&lt;br&gt;
type Note {&lt;br&gt;
  title: String!&lt;br&gt;
  body: String!&lt;br&gt;
}&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;In the example above, &lt;code&gt;Post&lt;/code&gt; is the type, and &lt;code&gt;title&lt;/code&gt; is the field.&lt;/p&gt;

&lt;h2&gt;
  
  
  Ways to build GraphQL APIs in Nest JS
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Schema-first&lt;/strong&gt; is a method where you manually define the GraphQL schema using SDL, then add the &lt;code&gt;typePaths&lt;/code&gt; property to the GraphQL Module options to tell it where to look for the schema.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code-first&lt;/strong&gt; is a method where the GraphQL schema is generated from Typescript classes and decorators, you do not write the GraphQL schema yourself.&lt;/p&gt;

&lt;h3&gt;
  
  
  Code-First method
&lt;/h3&gt;

&lt;p&gt;For this tutorial, we shall use the code-first approach where we shall add &lt;code&gt;autoSchemaFile&lt;/code&gt; to our GraphQL module options.&lt;/p&gt;

&lt;h4&gt;
  
  
  Installing dependencies
&lt;/h4&gt;

&lt;p&gt;Install the following dependencies that we shall use in this project.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install @nestjs/graphql graphql @nestjs/apollo @apollo/server typeorm @nestjs/typeorm pg @nestjs/config&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Configure TypeORM
&lt;/h4&gt;

&lt;p&gt;We shall use Postgres as our database and TypeORM as our ORM of choice.&lt;/p&gt;

&lt;p&gt;For the detailed method to configure Typeorm check out this &lt;a href="https://andisiambuku.hashnode.dev/user-authentication-with-passport-js-and-jwt-in-nest-js#heading-setting-up-typeorm" rel="noopener noreferrer"&gt;article&lt;/a&gt; and then we can proceed to the next section.&lt;/p&gt;

&lt;h4&gt;
  
  
  Configure GraphQL in the application module
&lt;/h4&gt;

&lt;p&gt;Since we are using the code-first method, we shall configure the &lt;code&gt;GraphQLModule&lt;/code&gt; with the following options:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Driver&lt;/strong&gt;:  this is the driver of our GraphQL server.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;autoSchemaFile&lt;/strong&gt;: this property's value indicates where the schema will be auto-generated.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;sortSchema&lt;/strong&gt;: this property will sort the items in the schema according to the way they would be in a dictionary because when the types are generated as they are in the module files.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in the imports array
GraphQLModule.forRoot&amp;lt;ApolloDriverConfig&amp;gt;({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      sortSchema: true,
    }),
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Creating the CRUD feature
&lt;/h3&gt;

&lt;p&gt;The beauty of Nest JS is that there is a simple way of building the GraphQL feature depending on the method you prefer whether code-first or schema-first.&lt;/p&gt;

&lt;h4&gt;
  
  
  Generating the feature using resource
&lt;/h4&gt;

&lt;p&gt;We shall be creating all the CRUD features and as such we will make use of the resource generator.&lt;em&gt;resource generator&lt;/em&gt; is a feature that auto-generates boilerplate for resources such as controllers, modules, and services. It helps save time and reduce the repetition of tasks.&lt;/p&gt;

&lt;p&gt;Run the command below&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nest generate resource note&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You will then see a prompt like this asking which transport layer you want.&lt;/p&gt;

&lt;p&gt;? What transport layer do you use?&lt;br&gt;
  REST API&lt;br&gt;
❯ GraphQL (code first)&lt;br&gt;
  GraphQL (schema first)&lt;br&gt;
  Microservice (non-HTTP)&lt;br&gt;
  WebSockets&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffm6o2es6qy34ml8gbyd6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffm6o2es6qy34ml8gbyd6.png" alt="GraphQL prompt" width="472" height="122"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select the GraphQL (code-first) option.&lt;/p&gt;
&lt;h4&gt;
  
  
  Entity
&lt;/h4&gt;

&lt;p&gt;The entity is where we define our database schema. The Nest JS docs refer to this as the model, but for simplicity let us can them the entity. The definition of our entity shall differ slightly from how it is defined in REST. We shall make use of the &lt;code&gt;@Field()&lt;/code&gt; and &lt;code&gt;@ObjectType()&lt;/code&gt; decorators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ObjectType, Field, Int } from '@nestjs/graphql';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@ObjectType()
@Entity()
export class Note {

  @Field(() =&amp;gt; Int)
  @PrimaryGeneratedColumn()
  id: number;

  @Field()
  @Column('text', { nullable: false })
  title: string;

  @Field()
  @Column('text', { nullable: false })
  body: string;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our schema for a note entity shall have two columns the title and body.&lt;/p&gt;

&lt;p&gt;The ID shall have the &lt;code&gt;@PrimaryGeneratedColumn()&lt;/code&gt; so that it auto-generates IDs for the data we key in and the &lt;code&gt;@Field(() =&amp;gt; Int)&lt;/code&gt; decorator with the type Int to ensure the type allowed is an integer.&lt;/p&gt;

&lt;p&gt;We use the &lt;code&gt;@Column('text', { nullable: false })&lt;/code&gt; on the body and title columns to validate that the input should not be null values.&lt;/p&gt;

&lt;h4&gt;
  
  
  Data Transfer Object (DTO)
&lt;/h4&gt;

&lt;p&gt;We shall have data transfer object files for both the creation and updation of our files. This will help perform data transformations and validation before storage in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { InputType, Field } from '@nestjs/graphql';

@InputType()
export class CreateNoteInput {
  @Field()
  title: string;

  @Field()
  body: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { CreateNoteInput } from './create-note.input';
import { InputType, Field, PartialType } from '@nestjs/graphql';

@InputType()
export class UpdateNoteInput extends PartialType(CreateNoteInput) {
  @Field()
  title: string;

  @Field()
  body: string;
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unlike the REST format of DTOs here we use the &lt;code&gt;@Column()&lt;/code&gt; decorator here we use the &lt;code&gt;@Field()&lt;/code&gt; decorator for the database columns.&lt;/p&gt;

&lt;h4&gt;
  
  
  Service
&lt;/h4&gt;

&lt;p&gt;The service is where we define our business logic functions. This helps keep the resolver modular.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// note.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Note } from './entities/note.entity';
import { CreateNoteInput } from './dto/create-note.input';
import { UpdateNoteInput } from './dto/update-note.input';

@Injectable()
export class NoteService {
  constructor(
    @InjectRepository(Note)
    private noteRepository: Repository&amp;lt;Note&amp;gt;,
  ) {}

  findAll(): Promise&amp;lt;Note[]&amp;gt; {
    return this.noteRepository.find();
  }

  findOne(id: number): Promise&amp;lt;Note&amp;gt; {
    return this.noteRepository.findOne({ where: { id } });
  }

  async create(createNoteInput: CreateNoteInput): Promise&amp;lt;Note&amp;gt; {
    const note = this.noteRepository.create(createNoteInput);
    return this.noteRepository.save(note);
  }

  async update(id: number, updateNoteInput: UpdateNoteInput) {
    const note = await this.findOne(id);
    this.noteRepository.merge(note, updateNoteInput);
    return this.noteRepository.save(note);
  }

  async remove(id: number): Promise&amp;lt;void&amp;gt; {
    await this.noteRepository.delete(id);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;create&lt;/code&gt; function is for creating a new note based on the data in the &lt;code&gt;createNoteInput&lt;/code&gt; DTO and then it saves the note using the create and save methods.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;update&lt;/code&gt; function is for updating a note based on the data provided in the &lt;code&gt;updateNoteInput&lt;/code&gt; DTO. It retrieves the note using its id and then merges the changes and then updates it in the database.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Resolver
&lt;/h4&gt;

&lt;p&gt;A &lt;strong&gt;resolver&lt;/strong&gt; is a file that provides instructions for turning GraphQL operations into data. They use the schema to return the data as specified.&lt;/p&gt;

&lt;p&gt;This is the equivalent of controllers in REST.&lt;/p&gt;

&lt;p&gt;The GraphQL operations that can be performed on data include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Mutation&lt;/strong&gt;: is used to make writes or updates to data in a GraphQL server. Operations like create, update, and delete are done using mutations.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Query&lt;/strong&gt;: is used to fetch data from a GraphQL server. It is a read operation that requests data without making any write operations in the database.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Subscriptions&lt;/strong&gt;: allow for real-time server updates. They enable the server to push data to clients when an event occurs. A use case for subscriptions is notifications.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Resolver, Query, Mutation, Args, Int } from '@nestjs/graphql';
import { NoteService } from './note.service';
import { Note } from './entities/note.entity';
import { CreateNoteInput } from './dto/create-note.input';
import { UpdateNoteInput } from './dto/update-note.input';

@Resolver(() =&amp;gt; Note)
export class NoteResolver {
  constructor(private readonly noteService: NoteService) {}

  @Mutation(() =&amp;gt; Note)
  async createNote(@Args('createNoteInput') createNoteInput: CreateNoteInput) {
    return this.noteService.create(createNoteInput);
  }

  @Query(() =&amp;gt; [Note], { name: 'notes' })
  findAll() {
    return this.noteService.findAll();
  }

  @Query(() =&amp;gt; Note, { name: 'note' })
  findOne(@Args('id', { type: () =&amp;gt; Int }) id: number) {
    return this.noteService.findOne(id);
  }

  @Mutation(() =&amp;gt; Note)
  updateNote(@Args('updateNoteInput') updateNoteInput: UpdateNoteInput) {
    return this.noteService.update(updateNoteInput.id, updateNoteInput);
  }

  @Mutation(() =&amp;gt; Note)
  removeNote(@Args('id', { type: () =&amp;gt; Int }) id: number) {
    return this.noteService.remove(id);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;@Resolver(() =&amp;gt; Note)&lt;/code&gt;: this decorator shows NoteResolver class is a GraphQL resolver for the 'Note' entity telling NestJS and the GraphQL framework that this class handles GraphQL queries and mutations related to the Note type.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;createNote&lt;/code&gt; mutation: The @Args('createNoteInput') decorator specifies that the createNote method expects an argument named createNoteInput, which should be of type CreateNoteInput.&lt;br&gt;
Inside the method, you call  &lt;code&gt;this.noteService.create(createNoteInput)&lt;/code&gt; function to create a new note and return it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;findAll&lt;/code&gt; query: This decorator marks the findAll method as a GraphQL query. Queries are used for retrieving data from the server.&lt;br&gt;
The { name: 'notes' } option specifies the name of the query, which will be used in the GraphQL schema.&lt;br&gt;
Inside the method, you call &lt;code&gt;this.noteService.findAll()&lt;/code&gt; to retrieve a list of all notes and return them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;findOne&lt;/code&gt; query: This decorator marks the findOne method as a GraphQL query. The { name: 'note' } option specifies the name of the query. The method expects an argument named id of type Int, and it uses &lt;code&gt;this.noteService.findOne(id)&lt;/code&gt; to retrieve a single note by ID and return it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;updateNote&lt;/code&gt; mutation: This decorator marks the updateNote method as a GraphQL mutation. The @Args('updateNoteInput') decorator specifies that the method expects an argument named updateNoteInput of type UpdateNoteInput. Inside the method, you call this.noteService.update(updateNoteInput.id, updateNoteInput) to update a note and return it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;removeNote&lt;/code&gt; mutation: This decorator marks the removeNote method as a GraphQL mutation. The @Args('id', { type: () =&amp;gt; Int }) decorator specifies that the method expects an argument named id of type Int. Inside the method, you call &lt;code&gt;this.noteService.remove(id)&lt;/code&gt;` to delete a note.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Module
&lt;/h4&gt;

&lt;p&gt;The module is where we define the metadata for libraries we use in our API.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
//note.module.ts&lt;br&gt;
import { Module } from '@nestjs/common';&lt;br&gt;
import { NoteService } from './note.service';&lt;br&gt;
import { NoteResolver } from './note.resolver';&lt;br&gt;
import { TypeOrmModule } from '@nestjs/typeorm';&lt;br&gt;
import { Note } from './entities/note.entity';&lt;/p&gt;

&lt;p&gt;@Module({&lt;br&gt;
imports: [TypeOrmModule.forFeature([Note])],&lt;br&gt;
providers: [NoteResolver, NoteService],&lt;br&gt;
})&lt;br&gt;
export class NoteModule {}&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here add the Typeorm module to the import or the note feature.&lt;/p&gt;

&lt;p&gt;Ensure you run the migration to create the columns in our database. In the event you have used the configuration in the suggested article then run your migration as follows:&lt;/p&gt;

&lt;p&gt;make migration: &lt;code&gt;npm run typeorm:generate-migration migrations/&amp;lt;name_of_migration&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;run migration: &lt;code&gt;npm run typeorm:run-migrations&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing the Endpoint
&lt;/h3&gt;

&lt;p&gt;One of the grand advantages of GraphQL is that we only make use of one endpoint as opposed to REST here we have multiple endpoints as per the operations you want to have for your data.&lt;/p&gt;

&lt;p&gt;Now that the feature is complete let us proceed to test the endpoint. We shall make use of the GraphQL playground at &lt;code&gt;http://localhost:3000/graphql&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After running the &lt;code&gt;npm run start&lt;/code&gt; command, you will see the schema auto-generated. It will look like the one below.&lt;/p&gt;

&lt;p&gt;//schema.gql&lt;/p&gt;




&lt;p&gt;THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)&lt;/p&gt;




&lt;p&gt;input CreateNoteInput {&lt;br&gt;
body: String!&lt;br&gt;
title: String!&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;type Mutation {&lt;br&gt;
createNote(createNoteInput: CreateNoteInput!): Note!&lt;br&gt;
removeNote(id: Int!): Note!&lt;br&gt;
updateNote(updateNoteInput: UpdateNoteInput!): Note!&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;type Note {&lt;br&gt;
body: String!&lt;br&gt;
id: Int!&lt;br&gt;
title: String!&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;type Query {&lt;br&gt;
note(id: Int!): Note!&lt;br&gt;
notes: [Note!]!&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;input UpdateNoteInput {&lt;br&gt;
body: String!&lt;br&gt;
id: Float!&lt;br&gt;
title: String!&lt;br&gt;
}&lt;/p&gt;

&lt;h4&gt;
  
  
  Create note
&lt;/h4&gt;

&lt;p&gt;To test the creation of a note ensure you check the schema for the format of the the request. According to our schema, the mutation should look like the one below. Add the mutation to the left panel and click the 'play' button.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;//create mutation&lt;br&gt;
mutation {&lt;br&gt;
  createNote(createNoteInput: {&lt;br&gt;
    title: "Test",&lt;br&gt;
    body: "Test body"&lt;br&gt;
  }) {&lt;br&gt;
    id&lt;br&gt;
    title&lt;br&gt;
    body&lt;br&gt;
  }&lt;br&gt;
}&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Falgnyh9ekpb9ku1f68xb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Falgnyh9ekpb9ku1f68xb.png" alt="Create note" width="800" height="405"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Find one note
&lt;/h4&gt;

&lt;p&gt;To test the fetching of a note ensure you check the schema for the format of the the request. According to our schema, the query should look like the one below. Add the query to the left panel and click the 'play' button.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;//find one query&lt;br&gt;
query {&lt;br&gt;
  note(id:1) {&lt;br&gt;
    id,&lt;br&gt;
    title,&lt;br&gt;
    body&lt;br&gt;
  }&lt;br&gt;
}&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F499mzp6d5rtyb1j5tdg2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F499mzp6d5rtyb1j5tdg2.png" alt="Find all" width="800" height="406"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Find all notes
&lt;/h4&gt;

&lt;p&gt;To test the fetching of all notes ensure you check the schema for the format of the the request. According to our schema, the query should look like the one below. Add the query to the left panel and click the 'play' button.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;//find all query&lt;br&gt;
query {&lt;br&gt;
  notes{&lt;br&gt;
    id,&lt;br&gt;
    title,&lt;br&gt;
    body&lt;br&gt;
  }&lt;br&gt;
}&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flcbzujaqn3a3myc6s6ao.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flcbzujaqn3a3myc6s6ao.png" alt="All notes" width="800" height="406"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Update note
&lt;/h4&gt;

&lt;p&gt;To test the updating of a note ensure you check the schema for the format of the request. According to our schema, the mutation should look like the one below. Add the mutation to the left panel and click the 'play' button.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;// update mutation&lt;br&gt;
mutation {&lt;br&gt;
  updateNote(updateNoteInput: {&lt;br&gt;
    id: 1,   &lt;br&gt;
    title: "Updated Title",&lt;br&gt;
    body: "Updated body"&lt;br&gt;
  }) {&lt;br&gt;
    id&lt;br&gt;
    title&lt;br&gt;
    body&lt;br&gt;
  }&lt;br&gt;
}&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9jbiq80jdzhjww0tlb7u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9jbiq80jdzhjww0tlb7u.png" alt="Update notes" width="800" height="405"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Delete note
&lt;/h4&gt;

&lt;p&gt;To test the deletion of a note ensure you check the schema for the format of the the request. According to our schema, the mutation should look like the one below. Add the mutation to the left panel and click the 'play' button.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;` //delete mutation&lt;br&gt;
mutation {&lt;br&gt;
  removeNote(id: 1) {&lt;br&gt;
    id&lt;br&gt;
    title&lt;br&gt;
    body&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkucubacrypevy58ar4q7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkucubacrypevy58ar4q7.png" alt="Remove notes" width="800" height="402"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The link to the project used in this tutorial is &lt;a href="https://github.com/andisiambuku/GraphQL-CRUD-API" rel="noopener noreferrer"&gt;here&lt;/a&gt;. Feel free to try out and comment your thoughts. Until next time may the code be with you.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://graphql.com/learn/what-is-graphql/" rel="noopener noreferrer"&gt;Learn GraphQL&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://graphql.org/learn/" rel="noopener noreferrer"&gt;GraphQL Organization&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.howtographql.com/basics/1-graphql-is-the-better-rest/" rel="noopener noreferrer"&gt;How to GraphQL&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.nestjs.com/graphql/quick-start" rel="noopener noreferrer"&gt;Nest JS Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>graphql</category>
      <category>nestjs</category>
    </item>
    <item>
      <title>User Authentication with Passport JS and JWT in Nest JS</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Tue, 22 Aug 2023 21:51:19 +0000</pubDate>
      <link>https://dev.to/andisiambuku/user-authentication-with-passport-js-and-jwt-in-nest-js-1ag3</link>
      <guid>https://dev.to/andisiambuku/user-authentication-with-passport-js-and-jwt-in-nest-js-1ag3</guid>
      <description>&lt;p&gt;&lt;strong&gt;Nest JS&lt;/strong&gt; is the lovechild of Typescript and Node JS (hurrah type-safety for the backend). The two come together to create a modular and robust framework that is easy to scale and maintain.&lt;/p&gt;

&lt;p&gt;This framework is ideal for developers who prefer convention over configuration as plenty of features come with the framework, for example, Decorators that define metadata for classes and Middleware that intercepts requests and responses for efficient data transmission.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ensure you have Node JS(version &amp;gt;= 16) installed on your machine and then proceed to the next section where we set up a REST API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;For this tutorial, we shall set up a REST API using the following steps:&lt;/p&gt;

&lt;p&gt;Open your operating system's terminal and key in the following commands.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm i -g @nestjs/cli&lt;/code&gt;&lt;br&gt;
&lt;code&gt;nest new blog-api&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The first command installs the nest CLI globally in your system. Note: installation takes a long time so don't be alarmed.&lt;/p&gt;

&lt;p&gt;Once done, the second command creates a project(feel free to call the project whatever name you wish). Ensure you choose REST from the options to create a REST API. The blog-api directory will have some boilerplate files, node modules, and a src folder with core files.&lt;/p&gt;
&lt;h2&gt;
  
  
  Setting up TypeORM
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;TypeORM&lt;/strong&gt; is an object-relational mapper that supports the latest JavaScript features from small to large-scale applications.&lt;/p&gt;

&lt;p&gt;The first step to configuring TypeORM is to install the relevant packages&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm i pg typeorm @nestjs/typeorm @nestjs/config&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The packages installed are as follows:&lt;/p&gt;

&lt;p&gt;typeorm - the package for TypeORM.&lt;/p&gt;

&lt;p&gt;pg - a postgres driver to connect typeorm and postgres database.&lt;/p&gt;

&lt;p&gt;@nestjs/config - Nest JS module for configuration.&lt;/p&gt;

&lt;p&gt;@nestjs/typeorm - Nest JS module for TypeORM.&lt;/p&gt;
&lt;h3&gt;
  
  
  Configuring a datasource file
&lt;/h3&gt;

&lt;p&gt;After installing the relevant packages, we need to configure a datasource file to enable the use of features like migrations.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;datasource&lt;/strong&gt; is a file where the connection settings for our database. It also sets the first database connection.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;migration&lt;/strong&gt; is a file with SQL queries that is used to modify an existing database and update its schema.&lt;/p&gt;

&lt;p&gt;Create a database using pgAdmin or psql CLI. If you are using the psql CLI then run the following command and add the database's name to the typeorm configs at the .env&lt;/p&gt;

&lt;p&gt;&lt;code&gt;createdb databasename&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create a file at the root of the Nest application and call it dataSource.ts.&lt;/p&gt;

&lt;p&gt;It is a good security practice to have sensitive data like database configurations stored in a .env file. For the port, host, username, password, and database add the configurations in a .env file and import the environment variables to this file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config'; //installed package
import { config } from 'dotenv';

config();

const configService = new ConfigService();

export default new DataSource({
  type: 'postgres',
  host: configService.get('TYPEORM_HOST'),
  port: configService.get('TYPEORM_PORT'),
  username: configService.get('TYPEORM_USERNAME'),
  password: configService.get('TYPEORM_PASSWORD'),
  database: configService.get('TYPEORM_DATABASE'),
  entities: ['src/**/*.entity.ts'],
  migrations: ['migrations/**/*{.ts,.js}'],
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us discuss the configurations in this file:&lt;/p&gt;

&lt;p&gt;const configService = new ConfigService();: This line creates an instance of a ConfigService class, which is likely a custom class used to manage configuration settings for the application. It seems to provide a way to retrieve configuration values.&lt;/p&gt;

&lt;p&gt;export default new DataSource({ ... });: This line exports a new instance of the DataSource class, which is the main configuration object used by TypeORM to connect to a database.&lt;/p&gt;

&lt;p&gt;Configuration Object Properties:&lt;/p&gt;

&lt;p&gt;type: 'postgres': Specifies that PostgreSQL is the database type being used.&lt;/p&gt;

&lt;p&gt;host: configService.get('TYPEORM_HOST'): Retrieves the database host from the configuration service using the key 'TYPEORM_HOST'.&lt;/p&gt;

&lt;p&gt;port: configService.get('TYPEORM_PORT'): Retrieves the database port from the configuration service using the key 'TYPEORM_PORT'.&lt;/p&gt;

&lt;p&gt;username: configService.get('TYPEORM_USERNAME'): Retrieves the database username from the configuration service using the key 'TYPEORM_USERNAME'.&lt;/p&gt;

&lt;p&gt;password: configService.get('TYPEORM_PASSWORD'): Retrieves the database password from the configuration service using the key 'TYPEORM_PASSWORD'.&lt;/p&gt;

&lt;p&gt;database: configService.get('TYPEORM_DATABASE'): Retrieves the database name from the configuration service using the key 'TYPEORM_DATABASE'.&lt;/p&gt;

&lt;p&gt;entities: ['src/*&lt;em&gt;/&lt;/em&gt;.entity.ts']: Specifies the paths to entity files. These files define the structure of your database tables and are used by TypeORM to interact with the database.&lt;/p&gt;

&lt;p&gt;migrations: ['migrations/*&lt;em&gt;/&lt;/em&gt;{.ts,.js}']: Specifies the paths to migration files. Migrations are scripts that manage changes to the database schema over time.&lt;/p&gt;

&lt;p&gt;Create a migrations folder at the root of the Nest JS project for our migration files.&lt;/p&gt;

&lt;p&gt;Add the following to the existing scripts in package.json to enable typeorm migrations to work.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "typeorm": "ts-node ./node_modules/typeorm/cli",
    "typeorm:run-migrations": "npm run typeorm migration:run -- -d ./dataSource.ts",
    "typeorm:generate-migration": "npm run typeorm -- -d ./dataSource.ts migration:generate",
    "typeorm:create-migration": "npm run typeorm -- migration:create",
    "typeorm:revert-migration": "npm run typeorm -- -d ./dataSource.ts migration:revert"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  App module
&lt;/h3&gt;

&lt;p&gt;Add the typeorm module along with the configurations to the  app module at imports array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { join } from 'path';
import { AuthModule } from './auth/auth.module';


// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();

const {
  TYPEORM_HOST,
  TYPEORM_USERNAME,
  TYPEORM_PASSWORD,
  TYPEORM_DATABASE,
  TYPEORM_PORT,
} = process.env;

@Module({
  imports: [TypeOrmModule.forRoot({
      type: 'postgres',
      host: TYPEORM_HOST,
      port: parseInt(TYPEORM_PORT),
      username: TYPEORM_USERNAME,
      password: TYPEORM_PASSWORD,
      database: TYPEORM_DATABASE,
      entities: [join(__dirname, '**', '*.entity.{ts,js}')],
    }),
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Adding the user authentication feature
&lt;/h3&gt;

&lt;p&gt;User authentication is an important feature in any application. It allows users to create accounts in our application and access features provided therein. It is also a security measure to protect user data.&lt;/p&gt;

&lt;p&gt;To create this feature we shall make use of the resource generator in Nest.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nest g resource auth&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It generates the entity, controller, module, and service files we require for this feature.&lt;/p&gt;

&lt;h3&gt;
  
  
  User Entity
&lt;/h3&gt;

&lt;p&gt;The first thing we do is to model the user. We shall create the database columns or the user entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//user.entity.ts
import {BaseEntity, PrimaryGeneratedColumn, Entity, Column, Unique,
OneToMany,} from 'typeorm';
import * as bcrypt from 'bcrypt';

@Entity()
@Unique(['email'])
export class User extends BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  username: string;

  @Column()
  email: string;

  @Column()
  password: string;

  @Column()
  salt: string;

  async validatePassword(password: string): Promise&amp;lt;boolean&amp;gt; {
    const hash = await bcrypt.hash(password, this.salt);
    return hash === this.password;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us discuss the code in this file.&lt;/p&gt;

&lt;p&gt;@Entity(): This decorator indicates that the class User is an entity, representing a database table. In this case, it represents the "User" table.&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/unique"&gt;@unique&lt;/a&gt;(['email']): This decorator specifies that the "email" column in the "User" table should have unique values. This helps enforce uniqueness for email addresses in the database.&lt;/p&gt;

&lt;p&gt;export class User extends BaseEntity { ... }: This defines the User class, which extends BaseEntity. BaseEntity is a class provided by TypeORM that contains common properties and methods for entities.&lt;/p&gt;

&lt;p&gt;@PrimaryGeneratedColumn('uuid'): This decorator indicates that the id property is a primary key column that will be generated using UUIDs (Universally Unique Identifiers).&lt;/p&gt;

&lt;p&gt;@Column(): These decorators indicate that the email, password, and salt properties are columns in the table. The email and password columns are required, while the salt column is used for password hashing.&lt;/p&gt;

&lt;p&gt;We shall hash user passwords with bcrypt before storing them in the database to secure user passwords.&lt;/p&gt;

&lt;p&gt;The salt is a randomly generated value that is attached to an encrypted password to uniquely identify it in the event two or more users (unknowingly) register with the same passwords.&lt;/p&gt;

&lt;h3&gt;
  
  
  User Data Transfer Object
&lt;/h3&gt;

&lt;p&gt;A data transfer object (DTO) is a design pattern used to define a data structure that carries data between different layers of an application, often between the client and the server. DTOs are used to encapsulate and transfer data in a structured and controlled way.&lt;/p&gt;

&lt;p&gt;We shall have the following DTOs for this feature: the login DTO and the signup DTO.&lt;/p&gt;

&lt;h3&gt;
  
  
  Signup DTO
&lt;/h3&gt;

&lt;p&gt;The DTO  is used to validate the inputs that we get from the user when they signup. We use the class validator library to validate the database columns.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//signup.dto.ts
import { IsString, IsEmail, MinLength, Matches } from 'class-validator';

export class SignupDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(8)
  //regex for password to contain atleast one uppercase, lowercase, number and special character
  @Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {
    message:
      'password must contain uppercase, lowercase, number and special character',
  })
  password: string;

  @IsString()
  username: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;export class SignupDto { ... }: This defines the SignupDto class.&lt;/p&gt;

&lt;p&gt;@IsEmail(): This decorator specifies that the email property should be a valid email address.&lt;/p&gt;

&lt;p&gt;@IsString(): This decorator specifies that the password and username properties should be of string type.&lt;/p&gt;

&lt;p&gt;@MinLength(8): This decorator specifies that the password property should have a minimum length of 8 characters.&lt;/p&gt;

&lt;p&gt;@Matches(/((?=.&lt;em&gt;\d)|(?=.&lt;/em&gt;\W+))(?![.\n])(?=.&lt;em&gt;[A-Z])(?=.&lt;/em&gt;[a-z]).*$/, { ... }): This decorator specifies that the password property should match a specific regex pattern that enforces certain complexity rules:&lt;/p&gt;

&lt;p&gt;(?=.*\d): At least one digit (number) should be present.&lt;/p&gt;

&lt;p&gt;(?=.*\W+): At least one special character should be present.&lt;/p&gt;

&lt;p&gt;(?=.*[A-Z]): At least one uppercase letter should be present.&lt;/p&gt;

&lt;p&gt;(?=.*[a-z]): At least one lowercase letter should be present.&lt;/p&gt;

&lt;p&gt;.&lt;em&gt;$: Match any characters (the .&lt;/em&gt; before $ ensures that the rule applies to the entire string).&lt;/p&gt;

&lt;p&gt;The provided message is used to specify a custom error message if the password does not meet the complexity requirements.&lt;/p&gt;

&lt;p&gt;password: string;: This declares the password property as a string within the DTO.&lt;/p&gt;

&lt;p&gt;username: string;: This declares the username property as a string within the DTO.&lt;/p&gt;

&lt;h3&gt;
  
  
  Login DTO
&lt;/h3&gt;

&lt;p&gt;This DTO is used to validate the inputs that we get from the user when they log in. We use the class validator library to validate the database columns.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//login.dto.ts
import { IsEmail, IsString } from 'class-validator';

export class LoginDto {
  @IsEmail()
  email: string;

  @IsString()
  password: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Login Response DTO
&lt;/h3&gt;

&lt;p&gt;This DTO is used to supply the database columns that are to be contained in the log-in response when a user logs in. We shall see this when we test the endpoints.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//loginResponse.dto.ts
export class LoginResponseDto {
  username: string;
  email: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  User service
&lt;/h3&gt;

&lt;p&gt;A service is used to manage the business logic and data manipulation from the repository. It helps with the separation of concerns and code reusability.&lt;/p&gt;

&lt;p&gt;We shall add the user service to the services folder as we shall have the functions that create and sign in a new user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//user.service.ts
import { Injectable } from '@nestjs/common';
import { User } from '../entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { SignupDto } from '../dto/signup.dto';
import * as bcrypt from 'bcrypt';
import { LoginDto } from '../dto/login.dto';
import { LoginResponseDto } from '../dto/loginResponse.dto';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository&amp;lt;User&amp;gt;,
  ) {}

  findById(id: string): Promise&amp;lt;User&amp;gt; {
    return this.userRepository.findOne({ where: { id } });
  }

  private async hashPassword(password: string, salt: string): Promise&amp;lt;string&amp;gt; {
    return bcrypt.hash(password, salt);
  }

  async create(signupDto: SignupDto): Promise&amp;lt;User&amp;gt; {
    const { email, password, username } = signupDto;
    const user = new User();

    user.salt = await bcrypt.genSalt();
    user.password = await this.hashPassword(password, user.salt);
    user.email = email;
    user.username = username;

    try {
      await user.save();
      return user;
    } catch (error) {
      throw error;
    }
  }

  async signIn(loginDto: LoginDto): Promise&amp;lt;LoginResponseDto&amp;gt; {
    const { email, password } = loginDto;
    const user = await this.userRepository.findOne({ where: { email } });

    if (user &amp;amp;&amp;amp; user.validatePassword(password)) {
      const userResponse = new LoginResponseDto();

      userResponse.username = user.username;
      userResponse.email = user.email;
      return userResponse;
    } else {
      return null;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's discuss this code:&lt;/p&gt;

&lt;p&gt;@Injectable(): This decorator indicates that the UserService class can be injected with dependencies. It's a crucial part of the Dependency Injection system in NestJS.&lt;/p&gt;

&lt;p&gt;constructor(@InjectRepository(User) private userRepository: Repository) { ... }: This constructor injects the userRepository as a dependency into the UserService class. The @InjectRepository decorator is part of TypeORM and injects the repository instance associated with the User entity.&lt;/p&gt;

&lt;p&gt;findById(id: string): Promise: This method queries the database using the injected userRepository to find a user by their id.&lt;/p&gt;

&lt;p&gt;private async hashPassword(password: string, salt: string): Promise: This is a private method that asynchronously hashes a password using the bcrypt library. The salt is passed as an additional parameter for added security.&lt;/p&gt;

&lt;p&gt;async create(signupDto: SignupDto): Promise: This method creates a new user based on the provided SignupDto and persists it to the database. It generates a unique salt, hashes the password, and then saves the user entity to the database.&lt;/p&gt;

&lt;p&gt;async signIn(loginDto: LoginDto): Promise: This method handles user authentication. It attempts to find a user by email from the database, and if found, it validates the password using the validatePassword method defined in the User entity. If the credentials are valid, a LoginResponseDto is returned, containing the user's username and email.&lt;/p&gt;

&lt;h3&gt;
  
  
  Configuring Passport JS and JWT
&lt;/h3&gt;

&lt;p&gt;Passport JS is an authentication middleware for Node JS applications. JSON Web Tokens(JWT) is a token-based authentication system that uses an encrypted token to manage user authentication.&lt;/p&gt;

&lt;p&gt;To configure the two for user authentication we begin by installing the relevant packages as shown below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install @nestjs/passport @nestjs/jwt passport-jwt&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We then create a constants file that shall contain an object that stores the JWT secret.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//constants.ts
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();

export const jwtConstants = {
  secret: process.env.JWT_SECRET,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;export const jwtConstants = { secret: process.env.JWT_SECRET };: This line of code exports an object named jwtConstants that contains the JWT secret. &lt;/p&gt;

&lt;p&gt;The JWT secret is used to sign and verify JWT tokens. In this case, the secret is retrieved from the environment variables using process.env.JWT_SECRET, which means you should have a variable named JWT_SECRET defined in your .env file.&lt;/p&gt;

&lt;h3&gt;
  
  
  Auth Module
&lt;/h3&gt;

&lt;p&gt;We add the JWT and Passport JS modules to the auth module at the imports array. or the passport module, configure the default strategy to be JWT. &lt;/p&gt;

&lt;p&gt;For the JWT module configure the secrets with the jwtConstants object. The signOptions is where we declare the lifetime of a town. The shorter the better to ensure user tokens are refreshed often as a security measure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//auth.module.ts
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './services/auth.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { jwtConstants } from './constants';
import { JwtStrategy } from './strategies/jwt.strategy';
import { UserService } from './services/user.service';

@Module({
  imports: [
    TypeOrmModule.forFeature([User]),
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: {
        expiresIn: '1h',
      },
    }),
  ],
  controllers: [AuthController],
  providers: [UserService, AuthService, JwtStrategy],
  exports: [JwtModule, PassportModule],
})
export class AuthModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Adding JWT to the auth service
&lt;/h3&gt;

&lt;p&gt;After configuring passport and JWT modules we proceed to use them in the auth service.&lt;/p&gt;

&lt;p&gt;We begin by creating a user-jwt interface. An interface in TypeScript is a way to define the structure of an object, specifying what properties it should have and their types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//user-jwt.interface.ts
import { LoginResponseDto } from '../dto/loginResponse.dto';

export interface UserJwtResponse {
  user: LoginResponseDto;
  accessToken: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;export interface UserJwtResponse { ... }: This line defines an interface named UserJwtResponse.  Here's what's defined within the UserJwtResponse interface:&lt;/p&gt;

&lt;p&gt;user: LoginResponseDto;: This property specifies that the user property of the UserJwtResponse object should be of type LoginResponseDto. It suggests that this property will contain data in the structure defined by the LoginResponseDto class.&lt;/p&gt;

&lt;p&gt;accessToken: string;: This property specifies that the accessToken property of the UserJwtResponse object should be of type string. This property is intended to hold a JSON Web Token (JWT) access token.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authentication service
&lt;/h3&gt;

&lt;p&gt;The auth service encapsulates user authentication logic within a NestJS application. It provides methods for validating users by ID, handling user registration, and managing user login.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../services/user.service';
import { SignupDto } from '../dto/signup.dto';
import { User } from '../entities/user.entity';
import { UserJwtResponse } from '../interfaces/user-jwt.interface';
import { LoginDto } from '../dto/login.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}
  async validateUserById(userId: string) {
    return await this.userService.findById(userId);
  }

  async signUp(signupDto: SignupDto): Promise&amp;lt;User&amp;gt; {
    return this.userService.create(signupDto);
  }

  async login(loginDto: LoginDto): Promise&amp;lt;UserJwtResponse&amp;gt; {
    const userResult = await this.userService.signIn(loginDto);

    if (!userResult) {
      throw new UnauthorizedException('Invalid Credentials!');
    }

    const payload = { userResult };
    const accessToken = await this.jwtService.sign(payload);

    const signInResponse: UserJwtResponse = { user: userResult, accessToken };

    return signInResponse;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us discuss the code: &lt;/p&gt;

&lt;p&gt;@Injectable(): This decorator indicates that the AuthService class can be injected with dependencies. This is a key feature of NestJS's Dependency Injection system.&lt;/p&gt;

&lt;p&gt;constructor(...): The constructor of the AuthService class receives two dependencies: userService and jwtService. These dependencies are automatically injected when an instance of AuthService is created.&lt;/p&gt;

&lt;p&gt;async validateUserById(userId: string) { ... }: This method is used to validate a user based on their userId. It uses the injected userService to find and return user information.&lt;/p&gt;

&lt;p&gt;async signUp(signupDto: SignupDto): Promise { ... }: This method is used to handle user registration. It takes a signupDto (presumably containing user signup information) and delegates the registration process to the userService. It returns the created user entity.&lt;/p&gt;

&lt;p&gt;async login(loginDto: LoginDto): Promise { ... }: This method handles user login. It takes a loginDto (presumably containing user login credentials) and proceeds as follows:&lt;/p&gt;

&lt;p&gt;It calls the signIn method of the userService to attempt user authentication.&lt;/p&gt;

&lt;p&gt;If authentication is successful, it generates an access token using the injected jwtService.&lt;/p&gt;

&lt;p&gt;It constructs a response object of type UserJwtResponse containing the authenticated user's information and the generated access token.&lt;/p&gt;

&lt;p&gt;If authentication fails (no user found or invalid credentials), it throws an UnauthorizedException.&lt;/p&gt;

&lt;p&gt;The signIn method is likely defined in the userService and handles user authentication, possibly returning the authenticated user's data or null if authentication fails.&lt;/p&gt;

&lt;h3&gt;
  
  
  Jwt strategy
&lt;/h3&gt;

&lt;p&gt;The JWT strategy class defines a JWT-based authentication strategy using Passport in a NestJS application. This strategy is an essential component of JWT-based authentication in the application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from '../services/auth.service';
import { jwtConstants } from '../constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    return await this.authService.validateUserById(payload.sub);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's discuss the code:&lt;/p&gt;

&lt;p&gt;@Injectable(): This decorator indicates that the JwtStrategy class can be injected with dependencies. It's important for Dependency Injection to work properly.&lt;/p&gt;

&lt;p&gt;export class JwtStrategy extends PassportStrategy(Strategy) { ... }: This line defines the JwtStrategy class, which extends PassportStrategy from the @nestjs/passport module. The Strategy parameter passed to PassportStrategy specifies the type of authentication strategy being implemented.&lt;/p&gt;

&lt;p&gt;constructor(private authService: AuthService) { ... }: The constructor of the JwtStrategy class receives an instance of the AuthService as a dependency. This dependency is automatically injected when an instance of JwtStrategy is created.&lt;/p&gt;

&lt;p&gt;super({ ... }): This line calls the constructor of the parent class (PassportStrategy) and provides options for configuring the JWT strategy. Specifically:&lt;/p&gt;

&lt;p&gt;jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(): This specifies that the JWT will be extracted from the Authorization header as a Bearer token.&lt;/p&gt;

&lt;p&gt;secretOrKey: jwtConstants.secret: This uses the JWT secret from the jwtConstants object (likely defined elsewhere) for token verification.&lt;/p&gt;

&lt;p&gt;async validate(payload: any) { ... }: This method is the heart of the JWT strategy. It's called when a JWT is successfully decoded and validated. The payload parameter contains the information stored in the JWT payload, including the user's ID (sub).&lt;/p&gt;

&lt;p&gt;Inside this method, the validateUserById method of the injected authService is called with the user's ID extracted from the payload.&lt;/p&gt;

&lt;p&gt;The validateUserById method is expected to return a user entity or null, indicating whether the user exists or not.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authentication controller
&lt;/h3&gt;

&lt;p&gt;The auth controller is responsible for handling authentication-related HTTP requests. It delegates the actual authentication and registration logic to the methods of the injected auth service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//auth.controller.ts
import { Body, Controller, Post, Put } from '@nestjs/common';
import { AuthService } from './services/auth.service';
import { SignupDto } from './dto/signup.dto';
import { User } from './entities/user.entity';
import { LoginDto } from './dto/login.dto';
import { UserJwtResponse } from './interfaces/user-jwt.interface';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post('signup')
  async signup(@Body() signupDto: SignupDto): Promise&amp;lt;User&amp;gt; {
    return this.authService.signUp(signupDto);
  }

  @Put('login')
  async login(@Body() loginDto: LoginDto): Promise&amp;lt;UserJwtResponse&amp;gt; {
    return this.authService.login(loginDto);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us discuss the code:&lt;/p&gt;

&lt;p&gt;@Controller('auth'): This decorator sets the base route for the AuthController to 'auth', which means that the routes defined within this controller will be accessed under the /auth endpoint.&lt;/p&gt;

&lt;p&gt;export class AuthController { ... }: This line defines the AuthController class.&lt;/p&gt;

&lt;p&gt;constructor(private readonly authService: AuthService) { ... }: The constructor of the AuthController class receives an instance of the AuthService as a dependency. This allows the controller to use methods and functionality provided by the AuthService.&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/post"&gt;@post&lt;/a&gt;('signup'): This decorator specifies that the signup method will handle HTTP POST requests to the /auth/signup endpoint.&lt;/p&gt;

&lt;p&gt;async signup(&lt;a class="mentioned-user" href="https://dev.to/body"&gt;@body&lt;/a&gt;() signupDto: SignupDto): Promise { ... }: This method is responsible for user registration. It receives a signupDto containing user registration data from the request body.&lt;/p&gt;

&lt;p&gt;The signupDto is passed to the signUp method of the injected authService, which handles the user registration process.&lt;/p&gt;

&lt;p&gt;The method returns a Promise which presumably represents the created user entity.&lt;/p&gt;

&lt;p&gt;@Put('login'): This decorator specifies that the login method will handle HTTP PUT requests to the /auth/login endpoint.&lt;/p&gt;

&lt;p&gt;async login(&lt;a class="mentioned-user" href="https://dev.to/body"&gt;@body&lt;/a&gt;() loginDto: LoginDto): Promise { ... }: This method is responsible for user login. It receives a loginDto containing user login credentials from the request body.&lt;/p&gt;

&lt;p&gt;The loginDto is passed to the login method of the injected authService, which handles the user authentication process.&lt;/p&gt;

&lt;p&gt;If authentication is successful, the method returns a Promise containing user information and an access token.&lt;/p&gt;

&lt;h3&gt;
  
  
  Running a migration
&lt;/h3&gt;

&lt;p&gt;Before testing the endpoints we need to create and run a migration to update the database schema with the user's table and columns. &lt;/p&gt;

&lt;p&gt;The command we shall use to create a migration is as shown below. It matches what we have configured in the datasource file.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm run typeorm:generate-migration migrations/CreateAuthTable&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then we follow that command with another one that runs the migration.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm run typeorm:run-migrations&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing the endpoints
&lt;/h2&gt;

&lt;p&gt;After successfully running the migration, we proceed to test the endpoints. Run the API using this command as it will run the API in watch mode.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm run start:dev&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Sign up endpoint
&lt;/h3&gt;

&lt;p&gt;In Postman, we create the body of the request we want to make which will create a new user.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk83xadp163pkat6etmbx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk83xadp163pkat6etmbx.png" alt="Signup endpoint" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Login endpoint
&lt;/h3&gt;

&lt;p&gt;In Postman, we create the body of the request we shall use to log in the user we created. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffz11zgbx4kfcr6byesxv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffz11zgbx4kfcr6byesxv.png" alt="Login endpoint" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The GitHub repository with the code for this project is &lt;a href="https://github.com/andisiambuku/Blog-API" rel="noopener noreferrer"&gt;here&lt;/a&gt;. Feel free to comment with any questions you may have. Until next time, may the code be with you.&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>jwt</category>
      <category>passportjs</category>
      <category>userauthentication</category>
    </item>
    <item>
      <title>Careers in the Data Field</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Tue, 22 Nov 2022 06:55:12 +0000</pubDate>
      <link>https://dev.to/andisiambuku/careers-in-the-data-field-2f5d</link>
      <guid>https://dev.to/andisiambuku/careers-in-the-data-field-2f5d</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Data is as old as time. Don't believe that? Well time itself is data and it has helped us understand our surroundings e.g evolution which is change(insert a variable of your liking) over time. There have been practitioners who have mastered the art of harnessing data and making sense of it so it can inform the world we live in today. Only recently have they been named and specific roles attached to their titles. They form the backbone of research and business performance in industries across the globe such as logistics, health care, agriculture, and even fashion.&lt;/p&gt;

&lt;p&gt;In this article, we shall explore some of the significant data practitioners, the roles they play, the tools they use, and the skills they have acquired that make them who they are in the data space. We shall also see the average they receive to motivate you to start your journey in the data field.&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Analyst
&lt;/h3&gt;

&lt;p&gt;A data analyst is a person who solves a business problem by collecting and interpreting data and communicates the insights effectively to the target audience e.g management of a company.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roles&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;They break down the business problem to understand the problem at hand.&lt;/li&gt;
&lt;li&gt;They gather the data from the necessary sources.&lt;/li&gt;
&lt;li&gt;They wrangle the data and clean it for analysis.&lt;/li&gt;
&lt;li&gt;The explore and analyze the data to find patterns in the data that relate to the business problem.&lt;/li&gt;
&lt;li&gt;They communicate the findings they derive from the data effectively with the use of visualizations and written reports to the target audience.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Skills&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SQL&lt;/li&gt;
&lt;li&gt;Tableau&lt;/li&gt;
&lt;li&gt;Microsoft Power BI&lt;/li&gt;
&lt;li&gt;Python or R&lt;/li&gt;
&lt;li&gt;Statistics&lt;/li&gt;
&lt;li&gt;Microsoft Excel&lt;/li&gt;
&lt;li&gt;Google Sheets&lt;/li&gt;
&lt;li&gt;Storytelling with data&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Salary&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;$422.65&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Scientist
&lt;/h3&gt;

&lt;p&gt;A Data Scientist is a person who solves business problems and then decides how data can be used to carry out those objectives. They construct algorithms and prediction models to extract the data the organization requires, design data modeling processes, assist in data analysis, and collaborate with others to share insights. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roles&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;They look for patterns and trends in datasets to get insights.&lt;/li&gt;
&lt;li&gt;Create data models and algorithms to predict outcomes.&lt;/li&gt;
&lt;li&gt;They use machine learning to enhance the quality of data or product offers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Skills&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Data Analysis skills&lt;/li&gt;
&lt;li&gt;Cloud Based tools e.g AWS
&lt;/li&gt;
&lt;li&gt;Machine Learning &lt;/li&gt;
&lt;li&gt;Big Data &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Salary&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;$633.98&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Engineer
&lt;/h3&gt;

&lt;p&gt;They are in charge of making sure that data transfer between servers and applications is seamless. The architecture used in projects involving data science is created and maintained. The task of storing and interpreting an enormous amount of data falls to data engineers. Expertise with data warehousing systems is important in this field.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roles&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use systematic techniques to design, build, and maintain data architectures.&lt;/li&gt;
&lt;li&gt;Data Collection from different sources.&lt;/li&gt;
&lt;li&gt;Automation of tasks.&lt;/li&gt;
&lt;li&gt;Identify trends using models they create.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Skills&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Database systems and tools.&lt;/li&gt;
&lt;li&gt;Data Processing with tools like Hadoop.&lt;/li&gt;
&lt;li&gt;ETL(Extract Transfer and Load)  tools.&lt;/li&gt;
&lt;li&gt;Data Warehousing with tools like RedShift.&lt;/li&gt;
&lt;li&gt;Machine Learning.&lt;/li&gt;
&lt;li&gt;Cloud Based tools like Azure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Salary&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;$2958.55&lt;/p&gt;

&lt;h3&gt;
  
  
  Business Intelligence Developer
&lt;/h3&gt;

&lt;p&gt;A business intelligence developer creates intelligence products that aim to improve business decision-making procedures. These consist of query systems, apps for data modeling, interactive dashboards, and data visualization tools.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roles&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;They create visualizations and reports.&lt;/li&gt;
&lt;li&gt;They write and maintain technical documentation.&lt;/li&gt;
&lt;li&gt;They collaborate with other developers and business analysts to get data.&lt;/li&gt;
&lt;li&gt;They create, deploy and maintain Business Intelligence solutions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Skills&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Data Analysis skills&lt;/li&gt;
&lt;li&gt;ETL tools.&lt;/li&gt;
&lt;li&gt;Business processes and procedures.&lt;/li&gt;
&lt;li&gt;Data Warehousing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Salary&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;$1775.13&lt;/p&gt;

&lt;h3&gt;
  
  
  Database Administrator
&lt;/h3&gt;

&lt;p&gt;A Database Administrator is in charge of managing the upkeep and security precautions for the company's databases. They maintain virus protection software, create account information for users who are authorized to access databases, and arrange databases so that users can quickly locate critical documents.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roles&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Data extraction and/or loading.&lt;/li&gt;
&lt;li&gt;Putting cybersecurity safeguards in place.&lt;/li&gt;
&lt;li&gt;Data authentication.&lt;/li&gt;
&lt;li&gt;Keeping track of how well hardware and software are performing.&lt;/li&gt;
&lt;li&gt;Setting up databases and servers.&lt;/li&gt;
&lt;li&gt;Managing private information ethically.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Skills&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Knowledge of database queries.&lt;/li&gt;
&lt;li&gt;Understand database theory and design.&lt;/li&gt;
&lt;li&gt;Establish, administer, and monitor data networks in collaboration with data architects and other IT professionals.&lt;/li&gt;
&lt;li&gt;Server installation and maintenance.&lt;/li&gt;
&lt;li&gt;Database management.&lt;/li&gt;
&lt;li&gt;Database structure languages like SQL or SQL/PSM.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Salary&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;$591.71&lt;/p&gt;

&lt;h3&gt;
  
  
  Statistician
&lt;/h3&gt;

&lt;p&gt;A Statistician is a person who gathers and examines data for a corporation. Statisticians analyze data sets for trends using both automated and manual data collection techniques, then present the patterns to corporate executives so that they can adjust their business operations.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roles&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Gathering information from several sources.&lt;/li&gt;
&lt;li&gt;Finding patterns in various data sets.&lt;/li&gt;
&lt;li&gt;Collaborating with other staff members to guarantee accurate and thorough data collection.&lt;/li&gt;
&lt;li&gt;Executive reports that are simple to read and clearly state the conclusions that can be made from a company's data.&lt;/li&gt;
&lt;li&gt;Putting statistical models into practice and coming to conclusions after collecting enough data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Skills&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Probability and Statistics&lt;/li&gt;
&lt;li&gt;Use a variety of statistical techniques to test hypotheses and make predictions&lt;/li&gt;
&lt;li&gt;Math, to turn complex sets of data into useful applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Salary&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;$612.84&lt;/p&gt;

&lt;p&gt;There are many more data-related careers such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Data Architect&lt;/li&gt;
&lt;li&gt;Data Journalist&lt;/li&gt;
&lt;li&gt;Machine Learning Engineer&lt;/li&gt;
&lt;li&gt;Data Miner&lt;/li&gt;
&lt;li&gt;Database Developer&lt;/li&gt;
&lt;li&gt;Data Curator&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  General skills data practitioners should all have:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Programming&lt;/li&gt;
&lt;li&gt;Collaborative&lt;/li&gt;
&lt;li&gt;Critical thinking&lt;/li&gt;
&lt;li&gt;Communication skills&lt;/li&gt;
&lt;li&gt;Analytical thinking&lt;/li&gt;
&lt;li&gt;Business intuition&lt;/li&gt;
&lt;li&gt;Problem-Solving skills&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Sidenote
&lt;/h4&gt;

&lt;p&gt;The salaries provide in this article are as per the following and subject to change:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sourced from Glassdoor(may vary with employers).&lt;/li&gt;
&lt;li&gt;Date of writing the article, 14/07/2022.&lt;/li&gt;
&lt;li&gt;Monthly remission.&lt;/li&gt;
&lt;li&gt;Location is Nairobi, Kenya.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Until next time, may the code be with you.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Data Stories: Medical Appointment Attendance in Brazil</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Fri, 03 Jun 2022 12:18:55 +0000</pubDate>
      <link>https://dev.to/andisiambuku/data-stories-medical-appointment-attendance-in-brazil-1oj7</link>
      <guid>https://dev.to/andisiambuku/data-stories-medical-appointment-attendance-in-brazil-1oj7</guid>
      <description>&lt;p&gt;Welcome to &lt;strong&gt;Data Stories&lt;/strong&gt;, this is a series where we will explore various data and deduce insights. We shall listen to the data as it tells us its story.&lt;/p&gt;

&lt;p&gt;We shall begin with a story about medical appointment attendance in Brazil. The data hails from &lt;a href="https://www.kaggle.com/datasets/joniarroba/noshowappointments" rel="noopener noreferrer"&gt;Kaggle&lt;/a&gt; and we shall explore it to find out whether or not Brazilians attend their medical appointments.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Side Note:&lt;/em&gt; This project was part of the Udacity Data Analytics Nanodegree and why not share it with fellow techies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table of Contents&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Questions For Analysis&lt;/li&gt;
&lt;li&gt;Data Wrangling&lt;/li&gt;
&lt;li&gt;Data Cleaning&lt;/li&gt;
&lt;li&gt;Exploratory Data Analysis&lt;/li&gt;
&lt;li&gt;Conclusions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Introduction: Dataset Description&lt;/strong&gt;&lt;br&gt;
The no-show appointments dataset is a collection of 100,000 medical appointments made by Brazilian patients who did not show up. It aims to help us figure out why they don't show up for their doctor's visits. There is enough data to tell a story about why people don't show up and to help mitigate this problem. This will aid in answering questions in the analysis portion and overcoming issues such as poor patient management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Questions For Analysis&lt;/strong&gt;&lt;br&gt;
The following are some of the questions that we seek to answer from the analysis of this dataset:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;How is the attendance to the appointments by the patients?&lt;/li&gt;
&lt;li&gt;What is the relationship between the independent variables and the dependent variable?&lt;/li&gt;
&lt;li&gt;What is the attendance of the patients on the Scholarship program to their medical appointments?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Data Wrangling&lt;/strong&gt;&lt;br&gt;
In this section the data is loaded into the notebook and we'll review it to see if there are any errors, which we'll address in the Data Cleaning section.&lt;/p&gt;

&lt;p&gt;We begin by importing the necessary libraries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#Import statements for all of the packages that are used.

import pandas as pd

import numpy as np

import seaborn as sns

import matplotlib.pyplot as plt

%matplotlib inline
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Data Wrangling&lt;/strong&gt;&lt;br&gt;
During the wrangling process there are few problems noticed with the dataset and they include:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2emkc20vj2h5gltwpycz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2emkc20vj2h5gltwpycz.png" alt="We begin by loading and inspecting the dataset" width="800" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Furt06hol6apns98bv5js.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Furt06hol6apns98bv5js.png" alt="We check the information about the dataset" width="800" height="312"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frph1prg594c95xyp9izr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frph1prg594c95xyp9izr.png" alt="Checking for missing data" width="800" height="247"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fure23pfbigjha7cqujfr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fure23pfbigjha7cqujfr.png" alt="Looking for duplicated data" width="800" height="63"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcoymkvbq1hxsp7hjihn6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcoymkvbq1hxsp7hjihn6.png" alt="Checking for the number of unique values" width="800" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fufbbr2mtav8cfxit99ya.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fufbbr2mtav8cfxit99ya.png" alt="Checking the datatypes of the column values" width="800" height="250"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Cleaning&lt;/strong&gt;&lt;br&gt;
The column names Hipertension and Handicap and are misspelled while SMS_ received doesn't require the underscore also No-show does not need the - sign.&lt;/p&gt;

&lt;p&gt;The Patient ID and Appointment ID columns are not relevant to this analysis.&lt;/p&gt;

&lt;p&gt;The datatypes of Scheduled day and Appointment day are incorrect. They are objects which is incorrect because they are dates which should be date datatypes.&lt;/p&gt;

&lt;p&gt;In this Data Cleaning section we shall make corrections to aforementioned problems.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9otaov7ycrtwao2lcxwx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9otaov7ycrtwao2lcxwx.png" alt="Renaming the column to Hypertension" width="800" height="171"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7sduyc64v3ij28c6v8r6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7sduyc64v3ij28c6v8r6.png" alt="Renaming the column to Handicap" width="800" height="169"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fac7nozver7r84yyhnjqy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fac7nozver7r84yyhnjqy.png" alt="Renaming the SMS received column" width="800" height="165"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbnb1k6py0l185pvmp6qh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbnb1k6py0l185pvmp6qh.png" alt="Changing the datatype of the Scheduled day column" width="800" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkii8zu7i5si3pnftqd2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkii8zu7i5si3pnftqd2.png" alt="Changing the datatype of the Appointment day column" width="800" height="246"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa2p8rlw98d10hqpgvspz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa2p8rlw98d10hqpgvspz.png" alt="Dropping columns we do not require" width="800" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5cmafk0eoqda3v3jk1g2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5cmafk0eoqda3v3jk1g2.png" alt="The final clean dataset" width="800" height="164"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Exploratory Data Analysis&lt;/strong&gt;&lt;br&gt;
The data is clean and ready for exploration. Here statistics shall be used to address the questions in the Introduction part and visualizations will also be created to answer the questions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzciqj0obwalw7px0b7lg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzciqj0obwalw7px0b7lg.png" alt="Answering the first analysis question" width="800" height="342"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd5rvcm4faj7vihh6921r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd5rvcm4faj7vihh6921r.png" alt="Pie chart showing the attendance of patients" width="800" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fadyaxzwtqdg6fnttxbi0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fadyaxzwtqdg6fnttxbi0.png" alt="Answering the second analysis question" width="800" height="346"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuokd7xj78n1dki8ny691.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuokd7xj78n1dki8ny691.png" alt="Answering the second analysis question" width="800" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4pt192byypovp408j9j5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4pt192byypovp408j9j5.png" alt="Answering the second analysis question" width="800" height="303"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnzauhfeuh3b9d5cpyw7b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnzauhfeuh3b9d5cpyw7b.png" alt="Bar plots showing independent variables against the dependent variables" width="800" height="372"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6reib3gkkz548pf5qwsl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6reib3gkkz548pf5qwsl.png" alt="Bar plots showing independent variables against the dependent variables" width="800" height="188"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The important details from the visualizations are as follows:&lt;/p&gt;

&lt;p&gt;Gender - there is a stark difference between males and females in terms of attendance to their medical appointments. The visualization show fewer males are attending their appointments compared to the females.&lt;/p&gt;

&lt;p&gt;SMS received - there is a large difference in the people who do receive SMS reminders for the appointments. A large number of those who receive the text do not show up to their appointments.&lt;/p&gt;

&lt;p&gt;Diabetes - there is a dismal trend in the patients who have Diabetes. The visualization shows they attend their appointments the least compared to those without the disease.&lt;/p&gt;

&lt;p&gt;Hypertension - there is a dismal trend in the patients who have Hypertension. The visualization shows they attend their appointments the least compared to those without the disease.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmsbityrexbq6xl8erhso.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmsbityrexbq6xl8erhso.png" alt="Answering the third analysis question" width="800" height="282"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff29svpx7lpduyfaw8kvm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff29svpx7lpduyfaw8kvm.png" alt="Pie chart showing the attendance of patients on the Scholarship program" width="800" height="208"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusions&lt;/strong&gt;&lt;br&gt;
In this section a detailed summary of the research is provide in relation to the questions posed in the Introduction section.&lt;/p&gt;

&lt;p&gt;From the study of 100,000 medical appointments by patients in Brazil we can draw the general conclusion that most of them do not attend their scheduled appointments. This is a sad state of affairs as medical appointments are very useful in early detection of diseases and also management of patients' conditions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;How is the attendance to the appointments by the patients?&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
The attendance of patients to their medical appointments is poor as only 20% of them attend their appointments that they schedule. 80% of patients fail to attend their appointments and this poses a challenge of management of their conditions such as Diabetes and Hypertension. This may have a domino effect of symptoms getting worse and even early deaths when this could be prevented by the patients attending their appointments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;What is the relationships between the independent variables and the dependent variable?&lt;/em&gt;&lt;/strong&gt; &lt;br&gt;
In terms of &lt;strong&gt;Gender&lt;/strong&gt;, there is a difference between males and females in terms of attendance to their medical appointments with fewer males are attending their appointments compared to the females.&lt;br&gt;
In terms of &lt;strong&gt;SMS received&lt;/strong&gt;, there is a large difference in the people who do receive SMS reminders for the appointments with a greater number of those who receive the text not showing up to their appointments.&lt;/p&gt;

&lt;p&gt;In terms of &lt;strong&gt;Diabetes&lt;/strong&gt;, there is a dismal trend in the patients who have Diabetes, they attend their appointments the least compared to those without the disease.&lt;/p&gt;

&lt;p&gt;In terms of &lt;strong&gt;Hypertension&lt;/strong&gt;, there is a dismal trend in the patients who have Hypertension, they attend their appointments the least compared to those without the disease.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;What is the attendance of the patients on the Scholarship program to their medical appointments?&lt;/em&gt;&lt;/strong&gt; &lt;br&gt;
The attendance of patients on the Scholarship program is poor with only 10% of them attending their scheduled appointments while an astounding 90% do not. This was a special feature to study because the Scholarship program dubbed Bolsa Familia is a welfare program intended to assist families in Brazil by providing them with an allowance, this move as made to assist them in part with their medical expenses. However, as the study shows this is not the case. This situation needs to be looked into by the government and measures put in place to ensure the program works for the people of Brazil and also they should be encouraged to attend their medical appointments.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Limitations in the research&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;There may be more factors around the reasons Brazilian citizens fail to show up to their medical appointments that may not have been factored in to this research and may affect the results of the study.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Additional research&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Additional research needs to be done on the Scholarship program to find out why the program intention was not met and why citizens on the Scholarship program are not responding to medical attention in terms of attending their scheduled appointments.&lt;/p&gt;

&lt;p&gt;REFERENCES&lt;/p&gt;

&lt;p&gt;Pereira, A. W. (2015). Bolsa Família and democracy in Brazil. Third World Quarterly, 36(9), 1682-1699.&lt;/p&gt;

&lt;p&gt;Here is the &lt;a href="https://github.com/andisiambuku/Appointment-Attendance" rel="noopener noreferrer"&gt;repo&lt;/a&gt; with the notebook. Feel free to leave a comment and critique or share more insights we could deduce.  &lt;/p&gt;

&lt;p&gt;Until next time, may the code be with you.&lt;/p&gt;

</description>
      <category>datascience</category>
      <category>python</category>
    </item>
    <item>
      <title>The Ultimate Guide To Getting Started in Data Science</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Sat, 02 Apr 2022 20:47:01 +0000</pubDate>
      <link>https://dev.to/andisiambuku/ultimate-guide-to-getting-started-in-data-science-3fb3</link>
      <guid>https://dev.to/andisiambuku/ultimate-guide-to-getting-started-in-data-science-3fb3</guid>
      <description>&lt;p&gt;I am sure if you follow #TechTwitter, you have come across this buzzword; Data Science. (Alongside Web 3 and JavaScript of course). &lt;/p&gt;

&lt;p&gt;Let us explore what Data Science is and find out what makes it so popular.&lt;/p&gt;

&lt;p&gt;Data Science is defined as deriving insights from a large amount of data. Data refers to the facts that are collected for analysis.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why learn Data Science?
&lt;/h3&gt;

&lt;p&gt;We live in a world that is data-driven meaning a large number of decisions that are made are arrived at with data at the core of the decision.&lt;br&gt;
Data also helps us understand the world better. Data on populations, trade e.tc help us better understand how the world works and how to optimize our world.&lt;br&gt;
With the genesis of digital devices such as smartphones, laptops, and even refrigerators we are constantly churning large amounts of data which can lead to actionable about ourselves, for example, our Social Media usage (yikes! probably might want to cut down on it)&lt;/p&gt;

&lt;h3&gt;
  
  
  What next?
&lt;/h3&gt;

&lt;p&gt;Now, that you know how vital Data Science is in our modern world, you presume we dive into the tools and skillset, No (we'll get their eager learner)&lt;/p&gt;

&lt;p&gt;The foundation for proper data science is understanding the issue or problem you are trying to solve. This will help guide the data science process and lead to very insightful actions from the data, for example, if the data consists of marketing and customer data then the problem should be defined as better targeted marketing.&lt;br&gt;
This is a simple checklist to guide the process&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Assess the issue &lt;/li&gt;
&lt;li&gt;Define the objective&lt;/li&gt;
&lt;li&gt;Define the problem
With the problem clearly defined you can proceed to the next aspect.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  The Data Science Process
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2FLearnPythonWithRune%2FDataScienceWithPython%2Fraw%2Fcd34587a04e855483609b3435659caeafcc8ce89%2F%2Fimg%2Fds-workflow.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fgithub.com%2FLearnPythonWithRune%2FDataScienceWithPython%2Fraw%2Fcd34587a04e855483609b3435659caeafcc8ce89%2F%2Fimg%2Fds-workflow.png" alt="data science process" width="800" height="400"&gt;&lt;/a&gt;&lt;br&gt;
With the problem defined you can go ahead and solve it via this process.&lt;br&gt;
&lt;strong&gt;Data Collection&lt;/strong&gt;&lt;br&gt;
The first step is to collect the data related to the problem you are trying to solve, for example, &lt;br&gt;
Problem: The extent of Covid-19 spread in the country&lt;br&gt;
Data: Reported Covid-19 cases in the country&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Preparation&lt;/strong&gt;&lt;br&gt;
Once you have collected the data, explore the data to find patterns and interests that suit the problem. This process is important as it helps you know the important things you need from the data and what to eliminate.&lt;br&gt;
Here is where data cleaning, the backbone of data science, lies. Missing data is handled and outliers are taken care of.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Analysis&lt;/strong&gt;&lt;br&gt;
Once you have clean data to work with you can analyze the data and select features of the data that will help create the best model, A data model is a conceptual model that organizes how different features of data relate to one another. This will assist in the analysis of your data and reveal insights.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Report on the data findings&lt;/strong&gt;&lt;br&gt;
Once the insights have been deduced, you move on to writing a report on your findings. You present the insights and visualize the results to help your audience better understand the outcome of the whole process. You can use data visualization tools such as charts and heat maps to present findings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implement Actions&lt;/strong&gt;&lt;br&gt;
A the end of the process you deduce the insight, for example, areas that require a lockdown to curb the spread of Covid-19. You present this as a recommendation to your audience and the go-ahead to implement it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tools and Skillset
&lt;/h3&gt;

&lt;p&gt;After going through the data process you have realized there are tools and skills that are required to fulfill this process. The tools and skillset are as follows;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Data Collection&lt;br&gt;
Tools: Cloud services such as AWS, Azure and Google Cloud Platform&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Data Cleaning&lt;br&gt;
Tools and Languages: SQL, Python, R, Databases, for example, Postgres and MongoDB&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Data Visualization&lt;br&gt;
Tools and Libraries: Excel, Tableau, Power BI, Matplotlib, Seaborn&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://twitter.com/AndisiAmbuku/status/1509630967140569092?s=20&amp;amp;t=kBVwyB3-5_Sb4g_h_oldUw" rel="noopener noreferrer"&gt;Link to resources&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Until next time, may the code be with you.&lt;/p&gt;

</description>
      <category>datascience</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Python for everyone: Mastering Python the Right Way</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Sun, 27 Feb 2022 20:56:21 +0000</pubDate>
      <link>https://dev.to/andisiambuku/python-for-everyone-mastering-python-the-right-way-1dp6</link>
      <guid>https://dev.to/andisiambuku/python-for-everyone-mastering-python-the-right-way-1dp6</guid>
      <description>&lt;p&gt;&lt;em&gt;Is Python for everyone?&lt;/em&gt; &lt;br&gt;
Yes!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;But I am an absolute beginner?&lt;/em&gt;&lt;br&gt;
It is for you.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;But I am from a completely unrelated field/career?&lt;/em&gt;&lt;br&gt;
It is for you too. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;But I am too old to learn?&lt;/em&gt;&lt;br&gt;
Unless you are dead, It is for you and us all!&lt;/p&gt;

&lt;p&gt;Python is one of the most popular programming languages with a wide variety of applications. The reason for its popularity is its simple syntax which reads like English. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Still not convinced it is for everyone? Here is another reason.&lt;/em&gt;&lt;br&gt;
Python has various use cases and applications in a variety of industries such as marketing, health, manufacturing e.t.c So no matter what field you are in Python can assist in making your work and that of your enterprise easier, faster and secure.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Now you are convinced Python is for everyone, especially you. Where do you go from here.&lt;/em&gt;&lt;br&gt;
You can begin by identifying the niche area you would like to delve into or an area that sparks your interest. Let us discuss some areas you can explore.&lt;/p&gt;

&lt;h2&gt;
  
  
  Python for what?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Web Development
&lt;/h3&gt;

&lt;p&gt;Python is widely used in developing web applications. It is commonly used to create the backend of the web applications. There are useful libraries like HTTP. The libraries assist in  managing content and the databases. &lt;br&gt;
There are frameworks like  &lt;a href="https://flask.palletsprojects.com/en/2.0.x/" rel="noopener noreferrer"&gt;Flask&lt;/a&gt;, &lt;a href="https://docs.djangoproject.com/en/4.0/" rel="noopener noreferrer"&gt;Django&lt;/a&gt;, &lt;a href="https://fastapi.tiangolo.com/" rel="noopener noreferrer"&gt;FastAPI&lt;/a&gt; that help create robust web applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  Data Analytics and Data Science
&lt;/h3&gt;

&lt;p&gt;This is an emerging field where data that is often in large amounts is used to draw insights that accelerate businesses. There are various modules that are used and the are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Numpy&lt;/li&gt;
&lt;li&gt;Matplotlib&lt;/li&gt;
&lt;li&gt;Pandas &lt;/li&gt;
&lt;li&gt;Seaborn&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Automation
&lt;/h3&gt;

&lt;p&gt;There are tasks which are repetitive and considered time consuming. Python can be used to write scripts that automate the tasks and save on time and cut down on costs. &lt;/p&gt;

&lt;h3&gt;
  
  
  Gaming
&lt;/h3&gt;

&lt;p&gt;Python can be used to create games. Amazing 3D games can be created using packages like Pykyra and Pygame. Games engines can be created using Python.&lt;/p&gt;

&lt;h3&gt;
  
  
  Embedded Systems
&lt;/h3&gt;

&lt;p&gt;Embedded systems are software that are set in hardware devices to perform special functions. An example is light sensors, where the software which is a microprocessor is used to power and control the hardware. In the event of an action the sensors are triggered and the either go on  or off. It also enables the communication of devices. &lt;/p&gt;

&lt;p&gt;There are many other applications. Take your time to explore as many as you can and select any that sparks your interest or that aligns with the career path you are on.&lt;/p&gt;

&lt;p&gt;Once you select your area, you can then move to selecting a learning path. There are several ways to go about this and they are as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Online Courses and Bootcamps
There are numerous resources and courses that you can use to get knowledge on Python. They range from free courses to paid courses. Select that which sits right with you. Here are some platforms you can access the courses:
Paid Platforms&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.udacity.com/course/introduction-to-python--ud1110" rel="noopener noreferrer"&gt;Udacity&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.udemy.com/courses/search/?src=ukw&amp;amp;q=Python" rel="noopener noreferrer"&gt;Udemy&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.coursera.org/courses?query=python" rel="noopener noreferrer"&gt;Coursera&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.pluralsight.com/browse/software-development/python" rel="noopener noreferrer"&gt;Pluralsight&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.tutorialspoint.com/categories/python" rel="noopener noreferrer"&gt;Tutorialspoint&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.tutorialspoint.com/certification/python-developer-s-guide-for-2022/index.asp" rel="noopener noreferrer"&gt;Python Developer’s Advanced Certification&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Free platforms&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/" rel="noopener noreferrer"&gt;Youtube&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pll.harvard.edu/course/cs50s-introduction-programming-python?delta=0" rel="noopener noreferrer"&gt;CS50&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.tutorialspoint.com/python/index.htm" rel="noopener noreferrer"&gt;Free Python Course on Tutorialspoint&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can opt for self-paced courses or join a coding bootcamps for your learning journey.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Coding challenges
Once you learn the basics you can test your knowledge with coding challenges. They help sharpen your skillset and help you practice the concepts you have learned. Some platforms you can challenge yourself are :&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.hackerrank.com/" rel="noopener noreferrer"&gt;Hackerrank&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/" rel="noopener noreferrer"&gt;Leetcode&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.codewars.com/" rel="noopener noreferrer"&gt;Codewars&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Hot tip&lt;/em&gt;: During interviews employers often take challenges from theses and other code challenge sites to test you at the technical stage.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Read the documentation&lt;br&gt;
Python have one of the best documentation out there. Make use of the &lt;a href="https://www.python.org/doc/" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;. Make it a habit to go through the docs during your learning and debugging process.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Join a community&lt;br&gt;
This is a paramount aspect for every developer. Join a community of developers whether physical or online. This will set you up for success and the community members will assist you be accountable and consistent. They serve to empower each other and foster growth of individuals. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;If you ant to go fast. go alone. If you wat to go far, go together&lt;/em&gt;&lt;br&gt;
~ African Proverb&lt;/p&gt;

&lt;h2&gt;
  
  
  Build as You Learn
&lt;/h2&gt;

&lt;p&gt;After you learn and test yourself, do not stop there. Keep practicing! Now you can dive into your niche area and practice.&lt;br&gt;
Make a habit of sharing what you build with the world. Write a blog post or share a screenshot of what your script can do. It promotes personal accountability and will help you network with others on the same path as you.&lt;/p&gt;

&lt;p&gt;Until next time, may the code be with you!&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Introduction to data structures and algorithms in Python</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Sun, 20 Feb 2022 21:39:10 +0000</pubDate>
      <link>https://dev.to/andisiambuku/introduction-to-data-structures-and-algorithms-in-python-2c06</link>
      <guid>https://dev.to/andisiambuku/introduction-to-data-structures-and-algorithms-in-python-2c06</guid>
      <description>&lt;p&gt;In this article we will explore the most fundamental concept in Python and programming. &lt;/p&gt;

&lt;p&gt;A good grasp of data structures and algorithms and the ways to implement them will assist you solve challenges using code and create robust solutions to real world problems. &lt;/p&gt;

&lt;p&gt;Data structures and algorithms can be a bit of a headache but by the end of this article you'll have the pain relief for that headache.&lt;/p&gt;

&lt;h2&gt;
  
  
  Data Structures
&lt;/h2&gt;

&lt;p&gt;A data structure is a special format in which data you can organize, process, retrieve and store data.&lt;br&gt;
There are various types each used for particular purposes. &lt;br&gt;
Data structures are important in assisting users organize data for easier use.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fpracticaldev%2Fimage%2Ffetch%2Fs--XzxY2Bkw--%2Fc_limit%252Cf_auto%252Cfl_progressive%252Cq_auto%252Cw_880%2Fhttps%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc67h1v1f1r5jsazd8xrg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fpracticaldev%2Fimage%2Ffetch%2Fs--XzxY2Bkw--%2Fc_limit%252Cf_auto%252Cfl_progressive%252Cq_auto%252Cw_880%2Fhttps%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc67h1v1f1r5jsazd8xrg.png" alt="chart showing data structures" width="800" height="334"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Built-in&lt;/strong&gt;&lt;br&gt;
I have covered this type in detail in the previous article &lt;a href="https://dev.to/andisiambuku/python-101-ultimate-guide-to-python-542g"&gt;PYTHON 101: ULTIMATE GUIDE TO PYTHON&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;List &lt;br&gt;
A list is a collection of data which is ordered and modifiable. It can have duplicate values.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Tuple &lt;br&gt;
A tuple is a collection of data which is ordered and unmodifiable. It can have duplicate values.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set &lt;br&gt;
A set is a collection of data which is unordered, unmodifiable and un-indexed. It cannot have duplicate values.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Dictionary &lt;br&gt;
A dictionary is a collection of data which is unordered and modifiable and indexed. It cannot have duplicate values.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;User-defined&lt;/strong&gt;&lt;br&gt;
User defined data structures allow users to control the functionality of the data structures and create them too.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stack - 
A stack is a linear data structure that stores data in a FILO(First In Last Out) format. A new element is added at one end and removed at only that end.
Deleting an item is called &lt;em&gt;pop&lt;/em&gt; while adding an item is called &lt;em&gt;push&lt;/em&gt;.
Illustration
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hzpzq9uwziugdddq89y.png" alt="stack" width="748" height="258"&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Implementation using a list&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;stack = []
stack.append("Andisi")
stack.append("Ambuku")
stack.append(2022)
print(f"Initial stack : {stack}")
Initial stack : ['Andisi', 'Ambuku', 2022]
stack.pop()
2022
stack.pop()
'Ambuku'
stack.pop()
'Andisi'
print(f"Stack after elements are removed : {stack}")
Stack after elements are removed : [] 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Queue - 
A queue is a linear data structure that stores items in FIFO(First In First Out) format. The last item to be added is the first to be removed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flweuidvwmw0fsyg6cgrp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flweuidvwmw0fsyg6cgrp.png" alt="queue" width="741" height="272"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;queue = []
queue.append("Andisi")
queue.append("Ambuku")
queue.append(2022)
print(f"Initial Queue is {queue}")
Initial Queue is ['Andisi', 'Ambuku', 2022]
queue.pop(0)
'Andisi'
queue.pop(0)
'Ambuku'
queue.pop(0)
2022
print(f"Queue after removing element: {queue}")
Queue after removing element: []


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Linked list - &lt;br&gt;
A linked list is a linear data structure where elements are not stored at adjoining memory locations. The elements are linked using pointers.&lt;br&gt;
Illustration&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi5byneky3bylbeevu5b1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi5byneky3bylbeevu5b1.png" alt="linked list" width="759" height="169"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Tree - &lt;br&gt;
A tree is a hierarchical data structure that looks like this&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.bing.com%2Fth%3Fid%3DOIP.5TR6ld9jT87LkRA8kHmiWgHaGL%26w%3D130%26h%3D108%26c%3D8%26rs%3D1%26qlt%3D90%26o%3D6%26pid%3D3.1%26rm%3D2" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.bing.com%2Fth%3Fid%3DOIP.5TR6ld9jT87LkRA8kHmiWgHaGL%26w%3D130%26h%3D108%26c%3D8%26rs%3D1%26qlt%3D90%26o%3D6%26pid%3D3.1%26rm%3D2" alt="tree" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;the top part is called the &lt;em&gt;root&lt;/em&gt; and the successive parts below it are called &lt;em&gt;nodes&lt;/em&gt;. The noes without successors or &lt;em&gt;children&lt;/em&gt; are called &lt;em&gt;leaf nodes&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Graph - 
A graph is a nonlinear data structure that has &lt;em&gt;edges&lt;/em&gt; and nodes (vertices). The edges connect two nodes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg4gnuspprhqvirjnvpcq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg4gnuspprhqvirjnvpcq.png" alt="graph" width="491" height="212"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hash map - 
A hash map is an indexed data structure. It uses a &lt;em&gt;hash function&lt;/em&gt;() to get the index with a corresponding key into an array of slots. The key is unique and cannot be changed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk1808v0dwkrdp1zt9sq5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk1808v0dwkrdp1zt9sq5.png" alt="hash map" width="450" height="310"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Heap - 
A heap is a data structure that is used to show a priority queue. This data structure gives the smallest element when an element(at random) is &lt;em&gt;popped&lt;/em&gt;. When items are &lt;em&gt;popped&lt;/em&gt; or &lt;em&gt;pushed&lt;/em&gt; the structure of the heap is maintained.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl8saqswwj6wvjliwx7sx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl8saqswwj6wvjliwx7sx.png" alt="heap" width="800" height="479"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Algorithms
&lt;/h2&gt;

&lt;p&gt;An algorithm is a set of rules that are followed to solve a problem. Input is given then the algorithm is executed and an output which is the solution results from the process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sorting algorithms&lt;/strong&gt;&lt;br&gt;
A sorting algorithm is a set of instructions accepts lists or arrays as input and arrange the items in a specific order.&lt;br&gt;
Sorting algorithms are useful in organizing data in a particular order. They make disorganized data more organized and easier to use.&lt;/p&gt;

&lt;p&gt;Examples of sorting algorithms include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bubble sort &lt;/li&gt;
&lt;li&gt;Insertion sort&lt;/li&gt;
&lt;li&gt;Merge sort&lt;/li&gt;
&lt;li&gt;Shell sort&lt;/li&gt;
&lt;li&gt;Selection sort&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Searching algorithms&lt;/strong&gt;&lt;br&gt;
Searching algorithms are sets of instructions used to search for an item in the data structure where it is contained. They are categorized into:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sequential search - 
This type of search algorithms are used on lists or arrays where they traverse every element sequentially and each element is checked until the solution is found then the process stops.
An example is Linear Search&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration from &lt;a href="https://www.geeksforgeeks.org/searching-algorithms/" rel="noopener noreferrer"&gt;Geeks for Geeks&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8noi8st5n831xmwz5syr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8noi8st5n831xmwz5syr.png" alt="linear search" width="800" height="292"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Interval Search - 
This type of search algorithms are used on sorted data structures for example, a sorted array. They divide the search space in two and keep doing so until the solution is found then the process stops.
An example is Binary Search.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration from&lt;a href="https://www.geeksforgeeks.org/searching-algorithms/" rel="noopener noreferrer"&gt;Geeks for Geeks&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqjbgpygad0cv7ixz9gyw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqjbgpygad0cv7ixz9gyw.png" alt="binary search" width="800" height="445"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Graph algorithms&lt;/strong&gt;&lt;br&gt;
A graph algorithm is a set of instructions that travel through (traverse) the nodes of a graph. It is used to find a particular path between nodes or a particular node.&lt;/p&gt;

&lt;p&gt;Graph algorithms have many uses one real world use is in taxi cab applications. The algorithm is implemented on the map feature to find the cheapest or the shortest path for a vehicle using a specified route.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Depth-first traversal - 
A depth-first search traverses the graph by checking the current node and then continuing to to one of its successors and repeating the same process. 
In case the current has no successor the algorithm goes back to its predecessor and then checks for successors and if the solution is found the search stops.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Illustration from &lt;a href="https://www.freecodecamp.org/news/graph-algorithms-explained/" rel="noopener noreferrer"&gt;Freecodecamp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2p45iwlyd6eit82lz2id.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2p45iwlyd6eit82lz2id.gif" alt="depth-first-algorithm" width="500" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Breadth-first traversal - 
The breadth-first search traverses the graph by checking the current node first and then enlarges it by including its successors to the consecutive level. 
This goes on all nodes it the current level then it continues to the next level until the solution is found the the search ends.
Illustration from &lt;a href="https://www.simplilearn.com/tutorials/data-structure-tutorial/bfs-algorithm#:~:text=Breadth-First%20Search%20Algorithm%20or%20BFS%20is%20the%20most,must%20move%20on%20to%20the%20next-level%20neighbor%20nodes." rel="noopener noreferrer"&gt;Simplilearn&lt;/a&gt;
&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F35tomdqql7w7pgkh445p.png" alt="breadth-first-algorithm" width="800" height="450"&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Properties of algorithms
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Finite&lt;br&gt;
An algorithm must end after a defined number of steps for any input entered.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Output specified&lt;br&gt;
An algorithm has to give an output as a result of the input it was given by a user. The output is the solution of the process.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Effective&lt;br&gt;
An algorithm's steps should be done accurately and within a finite amount of time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Input specified&lt;br&gt;
An algorithm has to be given input values to perform the process needed to generate a solution to a problem. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Definite&lt;br&gt;
An algorithm must have specified steps that it follows in generating the solution to a given problem. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Until next time, may the code be with you!&lt;/p&gt;

</description>
      <category>python</category>
      <category>algorithms</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>PYTHON 101: ULTIMATE GUIDE TO PYTHON</title>
      <dc:creator>Andisi (Roseland) Ambuku</dc:creator>
      <pubDate>Fri, 11 Feb 2022 07:10:10 +0000</pubDate>
      <link>https://dev.to/andisiambuku/python-101-ultimate-guide-to-python-542g</link>
      <guid>https://dev.to/andisiambuku/python-101-ultimate-guide-to-python-542g</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is Python?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Python is a general-purpose, interpreted, high-level programming language. It is a mouthful of a definition so let’s break it down;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;General-purpose means you can use Python in fields like automation, web applications, and data science. &lt;/li&gt;
&lt;li&gt;Interpreted means that you write Python code in a file called a source code and then the Python interpreter changes the source code to machine-readable code, a line at a time. &lt;/li&gt;
&lt;li&gt;High-level means that this language is simple to learn as you do not need to know the particulars of the computer to develop programs using Python.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Features of Python&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open Source: Python is free and easily accessible via their official website and being open source means that the source code that makes the language is available to the general public. You can access it on the &lt;a href="https://docs.python.org/3/tutorial/index.html" rel="noopener noreferrer"&gt;Python Website&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Object-Oriented Language: Python supports the use of objects and classes to write programs and build applications.&lt;/li&gt;
&lt;li&gt;Simplicity: Python is high-level programming and this makes it easy to understand, learn and code in. &lt;/li&gt;
&lt;li&gt;Portability: Python is the portable meaning if there is Python code on a Windows machine it can run on another machine with a different operating system like Linux.&lt;/li&gt;
&lt;li&gt;Dynamically Typed: this means that there is no need to specify the type for example int for an integer value as it is decided at the run time of the program.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Installation&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Download the latest version &lt;a href="https://www.python.org/downloads/" rel="noopener noreferrer"&gt;here&lt;/a&gt;. &lt;/li&gt;
&lt;li&gt;Once downloaded, add Python to the path variable in your machine and &lt;/li&gt;
&lt;li&gt;Follow the prompts to install it. &lt;/li&gt;
&lt;li&gt;Choose a code editor such as &lt;a href="https://code.visualstudio.com/Download" rel="noopener noreferrer"&gt;VS Code&lt;/a&gt;, PyCharm, Kite, or Sublime Text. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now you are ready to begin coding in Python!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: It is better to select a Python version that has security as opposed to those with bug fixes. It ensures the security of the programs you will write. At the time of writing this article, it is version 3.8.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax in Python&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Comments&lt;/strong&gt;&lt;br&gt;
These describe what a piece of code does and why it was written. The Python interpreter ignores comments when it executes the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# This is a comment on a single line.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Identifiers&lt;/strong&gt;&lt;br&gt;
These are names that identify objects such as functions and variables. The name of an identifier needs to begin with a letter or an underscore ( _ ). &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keywords&lt;/strong&gt;&lt;br&gt;
These are words with special meaning and cannot be used for any other purpose other than what they stand for. &lt;br&gt;
Examples &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;False &lt;/li&gt;
&lt;li&gt;class &lt;/li&gt;
&lt;li&gt;finally &lt;/li&gt;
&lt;li&gt;return &lt;/li&gt;
&lt;li&gt;global&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Literals&lt;/strong&gt;&lt;br&gt;
These are the values that are assigned to variables or constants. There are four types which are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;String literals&lt;/li&gt;
&lt;li&gt;Numeric literals&lt;/li&gt;
&lt;li&gt;Boolean literals&lt;/li&gt;
&lt;li&gt;Special literals&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Indentation and White spaces&lt;/strong&gt;&lt;br&gt;
In Python indentation and white spaces are used to create the code structure.&lt;br&gt;
Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def value():
    i = 13
    max = 100
    while (i &amp;lt; max):
        print(i)
        i = i + 1

# call function value
value()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Variables&lt;/strong&gt;&lt;br&gt;
A variable is a name that is used to specify a location in memory. When you first assign a value to a variable it is created and stored in memory. As you continue creating your program you can change the value of the variable.&lt;br&gt;
Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;middle_name = 'Andisi'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Standards for creating variables in Python&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A variable must begin with an underscore or a letter.&lt;/li&gt;
&lt;li&gt;The keywords in Python cannot be used to name a variable.&lt;/li&gt;
&lt;li&gt;Variable names are case-sensitive for example, food, Food, and FOOD are three different variables.&lt;/li&gt;
&lt;li&gt;A variable name cannot begin with a number.&lt;/li&gt;
&lt;li&gt;A variable name can only contain underscores and alphanumeric characters (0-9, a-z, and _ ).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Operators&lt;/strong&gt;&lt;br&gt;
Operators are used in performing operations on values and variables. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Arithmetic operators – These are used to perform mathematical operations on numerical values
Addition +
Subtraction -
Multiplication * 
Division /
Modulus % &lt;/li&gt;
&lt;li&gt;Assignment operators – these are used in assigning values to variables. See example at &lt;a href="https://www.w3schools.com/python/python_operators.asp" rel="noopener noreferrer"&gt;W3 Schools&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Comparison operators – these are used in comparing two values
Equal = =
Not equal  ! =
Greater than &amp;gt;
Less than &amp;lt;
Greater than or equal to &amp;lt; =
Less than or equal to &amp;gt;=
&lt;/li&gt;
&lt;li&gt;Logical operators – these are used in combining conditional statements. They include, and, or, not.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Data types&lt;/strong&gt;&lt;br&gt;
A data type is the classification of data in Python. The following are the standard datatypes in python:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Text – this is a data type that consists of text written as a string. It is written using single, double, and triple quotes.
Example
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;learning = 'My first string'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;Numeric – this is a data type that represents numbers. They include:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Integers – These are positive or negative whole numbers. They are indicated using int.&lt;br&gt;
Float – These are numerical values with decimal points. They are indicated using float&lt;br&gt;
Complex numbers – These are complex class values. They look like this, (real part) + (imaginary part)k for example 3+4k. They are indicated using complex&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sequence – This is a data type that is a collection of ordered similar or different data types. The sequence stores multiple values in an ordered way.
List – This is an ordered and modifiable collection of data that allows duplicate values.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fruits = ['mango', 'orange', 'grapes', 'pineapple']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Tuple – This is an ordered and unmodifiable collection of data that allows duplicate values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;drinks = ('water', 'soda', 'mocktails', 'yogurt')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Mapping – This is a data type that is used to store values much like a map.
Dictionary -This contains key and value pairs. It is an unordered and unmodifiable collection of values.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;person = {'name':'Andisi', 'gender' :'female', 'country': 'Kenya',}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Set – This is an unordered collection of values that is mutable. It is indicated as 'set'&lt;br&gt;
Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pets = {'cat', 'dog', 'parrot', 'fish'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Boolean – This data type has two values, true or false.
Example&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Control Flow&lt;/strong&gt;&lt;br&gt;
This is the order of code execution in a program to arrive at various specified decisions. The control flow is made possible using if statements, loops, and function calls.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If... Else statements
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;r = 4
if r &amp;lt; 0:
    print('r is a negative number')
else:
    print('r is a positive number')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;For loops
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fruits =['mango', 'orange', 'grapes', 'pineapple']
for fruit in fruits:
    print(fruit)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;While loops
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;t = 0
while t &amp;lt; 6:
    print(t)
    t = t + 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Classes&lt;/strong&gt;&lt;br&gt;
A class is a “blueprint” for creating objects. Python is an object-oriented programming language and as such everything is an object and they have methods and properties. Classes are created to create objects.&lt;br&gt;
Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Human:
    pass
print(Human)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Until next time, may the code be with you!&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
