<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hasitha Chandula on Medium]]></title>
        <description><![CDATA[Stories by Hasitha Chandula on Medium]]></description>
        <link>https://medium.com/@hasitha-chandula?source=rss-11df3e0b5159------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*BcnmgPsKmP3HH6mbsaksrA.jpeg</url>
            <title>Stories by Hasitha Chandula on Medium</title>
            <link>https://medium.com/@hasitha-chandula?source=rss-11df3e0b5159------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasitha-chandula/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simplifying API Calls in React with Custom Hooks]]></title>
            <link>https://hasitha-chandula.medium.com/simplifying-api-calls-in-react-with-custom-hooks-f0a3ba555088?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0a3ba555088</guid>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 16:38:09 GMT</pubDate>
            <atom:updated>2024-02-27T16:38:09.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VkcI2zjx4kl1rzRz" /></figure><h3>Introduction</h3><p>In modern web development, efficiently managing API requests is crucial for providing a seamless user experience. React’s custom hooks offer a powerful way to encapsulate and reuse logic across components. In this article, we explore two custom hooks, useQuery and useMutation, designed to handle data fetching and data mutation operations with ease. These hooks leverage Axios for making HTTP requests and are built with TypeScript for type safety and better developer experience.</p><h3>Setting Up Axios with Interceptors</h3><p>Before diving into the hooks, let’s set up an Axios instance with request and response interceptors to manage API tokens and handle 401 Unauthorized errors gracefully.</p><pre>import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from &#39;axios&#39;;<br><br>import { API_URL_V1 } from &#39;@/utils/constants&#39;;<br><br>interface CustomAxiosRequestConfig extends AxiosRequestConfig {<br>  _retry?: boolean;<br>}<br><br>const http: AxiosInstance = axios.create({<br>  baseURL: API_URL_V1,<br>  timeout: 30000 * 2,<br>});<br><br>async function getAccessTokenUsingRefreshToken(): Promise&lt;string&gt; {<br>  // Implemet logic to get new access token using refresh token<br>  return &#39;&#39;;<br>}<br><br>let isRefreshing = false;<br>let failedQueue: ((token: string) =&gt; void)[] = [];<br><br>http.interceptors.request.use(async (config) =&gt; {<br>  config.headers.authorization = `Bearer ${localStorage.getItem(<br>    &#39;ACCESS_TOKEN&#39;<br>  )}`;<br>  return config;<br>});<br><br>http.interceptors.response.use(<br>  (response: AxiosResponse) =&gt; {<br>    return response;<br>  },<br>  async (error) =&gt; {<br>    const originalRequest: CustomAxiosRequestConfig = error.config;<br><br>    originalRequest.headers = {<br>      ...originalRequest.headers,<br>    };<br><br>    if (error.response.status === 401 &amp;&amp; !originalRequest._retry) {<br>      if (isRefreshing) {<br>        try {<br>          const accessToken = await new Promise&lt;string&gt;((resolve) =&gt; {<br>            failedQueue.push((newAccessToken) =&gt; {<br>              resolve(newAccessToken);<br>            });<br>          });<br><br>          originalRequest.headers.authorization = `Bearer ${accessToken}`;<br>          return axios(originalRequest);<br>        } catch (error) {<br>          // If getting a new access token using refresh token also fails, show an alert message<br>          console.log(&#39;Failed to refresh access token using refresh token&#39;);<br>          // You can show an alert message here<br>        }<br>      } else {<br>        isRefreshing = true;<br>        originalRequest._retry = true;<br><br>        const newAccessToken = await getAccessTokenUsingRefreshToken();<br><br>        isRefreshing = false;<br>        localStorage.setItem(&#39;ACCESS_TOKEN&#39;, newAccessToken);<br><br>        originalRequest.headers.authorization = `Bearer ${newAccessToken}`;<br>        failedQueue.forEach((prom) =&gt; prom(newAccessToken));<br>        failedQueue = [];<br><br>        return axios(originalRequest);<br>      }<br>    }<br><br>    return Promise.reject(error.response);<br>  }<br>);<br><br>export default http;</pre><h3>The useQuery Hook</h3><p>The useQuery hook is designed for fetching data. It manages loading states, errors, and optionally, pagination metadata.</p><h4>Hook Definition</h4><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { toast } from &#39;react-toastify&#39;;<br><br>import http from &#39;@/services/http&#39;;<br><br>export interface Meta {<br>  totalPages: number;<br>  total: number;<br>}<br><br>interface IProps {<br>  url: string;<br>  disableOnLoad?: boolean;<br>  customHeaders?: object;<br>  page?: number;<br>  pageSize?: number;<br>}<br><br>function useQuery&lt;Resource&gt;({<br>  url,<br>  disableOnLoad,<br>  customHeaders = {},<br>}: IProps) {<br>  const [data, setData] = useState&lt;Resource | null&gt;(null);<br>  const [meta, setMeta] = useState&lt;Meta | null&gt;(null);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState&lt;unknown | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    if (!disableOnLoad) {<br>      fetchData();<br>    }<br>  }, []);<br><br>  const fetchData = async () =&gt; {<br>    setLoading(true);<br>    setData(null);<br>    setError(null);<br>    const headers = {<br>      headers: {<br>        ...customHeaders,<br>      },<br>    };<br>    try {<br>      const response = await http.get(url, headers);<br>      setLoading(false);<br>      setData(response?.data.data);<br>      if (response.data?.meta) {<br>        setMeta({<br>          total: response.data?.meta?.total,<br>          totalPages: response.data?.meta?.totalPages,<br>        });<br>      } else {<br>        setMeta({<br>          total: 0,<br>          totalPages: 0,<br>        });<br>      }<br>      return {<br>        success: true,<br>        data: response?.data,<br>        errors: null,<br>      };<br>    } catch (err: any) {<br>      setLoading(false);<br>      setError(err);<br>      setMeta({<br>        total: 0,<br>        totalPages: 0,<br>      });<br>      if (err.status === 403) {<br>        toast.error(&quot;Don&#39;t have permissions&quot;);<br>      }<br>      return {<br>        success: false,<br>        data: null,<br>        errors: err,<br>      };<br>    }<br>  };<br><br>  return { error, loading, data, retry: fetchData, meta };<br>}<br><br>export { useQuery };</pre><h4>Usage Example</h4><pre>const { data, loading, error } = useQuery&lt;MyDataType&gt;({ url: &#39;/data&#39; });</pre><p>This hook simplifies fetching data and handling loading states, and errors automatically.</p><h3>The useMutation Hook</h3><p>The useMutation hook handles creating, updating, or deleting data. It&#39;s versatile, supporting custom HTTP methods and headers.</p><h4>Hook Definition</h4><pre>import { useState } from &#39;react&#39;;<br>import { toast } from &#39;react-toastify&#39;;<br>import { AxiosError } from &#39;axios&#39;;<br><br>import { HTTP_TYPES } from &#39;@/utils/constants&#39;;<br>import http from &#39;@/services/http&#39;;<br><br>interface IProps {<br>  url: string;<br>}<br><br>function useMutation&lt;Resource&gt;({ url }: IProps) {<br>  const [loading, setLoading] = useState(false);<br><br>  const mutate = async (<br>    body: object,<br>    method?: HTTP_TYPES,<br>    customHeaders?: object,<br>    requestUrl?: string<br>  ) =&gt; {<br>    setLoading(true);<br><br>    const headers = {<br>      headers: {<br>        ...customHeaders,<br>      },<br>    };<br>    try {<br>      const response = await http[method || HTTP_TYPES.POST](<br>        requestUrl || url,<br>        body,<br>        headers<br>      );<br>      setLoading(false);<br>      return {<br>        success: true,<br>        data: response?.data?.data as Resource,<br>        errors: null,<br>      };<br>    } catch (error) {<br>      const err = error as AxiosError;<br>      setLoading(false);<br>      if (err.status === 403) {<br>        toast.error(&quot;Don&#39;t have permissions&quot;);<br>      }<br>      return {<br>        success: false,<br>        data: null,<br>        errors: err,<br>      };<br>    }<br>  };<br><br>  return { loading, mutate };<br>}<br><br>export { useMutation };</pre><h4>Usage Example</h4><pre>const { mutate, loading } = useMutation&lt;MyDataType&gt;({ url: &#39;/data&#39; });<br><br>const handleSubmit = async (data: MyDataType) =&gt; {<br>  const result = await mutate(data, HTTP_TYPES.POST);<br>  if (result.success) {<br>    // Handle success<br>  } else {<br>    // Handle error<br>  }<br>};</pre><p>The useMutation hook streamlines data mutations, offering a simple interface for complex operations.</p><h3>Conclusion</h3><p>The useQuery and useMutation hooks abstract away the complexities of API interactions in React applications. By encapsulating Axios requests within these hooks, developers can focus on building their application logic rather than dealing with the intricacies of HTTP requests and state management. Using TypeScript generics ensures that these hooks are both flexible and type-safe, accommodating various data types without compromising on code quality or developer experience.</p><p>Incorporating these hooks into your React project not only simplifies data fetching and mutation operations but also enhances the maintainability and scalability of your codebase. Whether building a simple application or a complex web platform, these custom hooks are invaluable tools in your React development arsenal.</p><p>GitHub URL: <a href="https://github.com/Hasi6/react-hooks-for-handle-http-requests">https://github.com/Hasi6/react-hooks-for-handle-http-requests</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0a3ba555088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Future of user Interface Design]]></title>
            <link>https://hasitha-chandula.medium.com/future-of-user-interface-design-3ff16c895152?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff16c895152</guid>
            <category><![CDATA[ui-design-tools]]></category>
            <category><![CDATA[ui-desings-in-future]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Sat, 26 Mar 2022 07:48:42 GMT</pubDate>
            <atom:updated>2022-03-26T07:56:23.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WyqcHz9MCvmIlu_-Sl-2w.jpeg" /></figure><p>Over the last few decades, user interfaces, have played a huge role in computing. And keep updating every day.</p><h3><strong>What is UI Design?</strong></h3><p>UI Design is a graphical layout which includes buttons that users can press, text they can read, the graphics, sliders, text entry boxes, and any other objects with which the user interacts. This includes transitions, interface animations and every single micro-interaction and any sort of visual element we can consider as UI Design.</p><h3>Different user interface designs in future</h3><p>Apart from computing UI designs, voice UI designs, AR (augmented reality), and VR (Virtual Reality) allows for more interactions from users. Most of companies are using AR and VR UI designs to increase their revenue. The future of UI designs is emerging rapidly with the help of AR, VR and voice assistants.With the advancement of technology, the focus of User Interface has shifted from usability to appearance and feel to stand-out interfaces. It’s affecting the way we engage with others. let’s find out the some UI designs in future,</p><h4>1. Brain Computer Interface</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rLi0-1H4zyzCw8lAfnlZg.jpeg" /></figure><p>BCI (Brain computer interface) design AKA direct neural interface is a communication tool between a users brain and an system. Neurons in our brain transmit signals to other nerve cells. These neurons produce brain waves, which operate the system in the brain-computer interface. The BCI captures brain waves and delivers them to a computer system to complete the work at hand. The brain generates electric impulses in response to our ideas, and each thought has its own brain wave pattern. The wave signal is used to control an object and communicate a concept.</p><h4>2. Wearable Computers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Udb8f-pt_mEFUiXBY2orPA.png" /></figure><p>Wearable computers (or wearables) are tiny electronic devices that may be worn on the body (mostly wrist). Smart watches, wristbands, rings, pins, eyeglasses, and other accessories are examples. Wearables act as a helpful hand in completing physical chores and reminding you of your daily routine. The majority of gadgets are employed for health-related duties such as monitoring heart rate, cholesterol, calorie consumption, and so on.Using a smart watch as an example, linking it with a smartphone allows it to emulate several of the smartphone’s features. It delivers calling, email, message, and twitter notifications once it is linked.Google Glass and AI-powered hearing aids, for example, are highly developed instances of wearable technology.</p><h4>3. Voice User Interface</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05sbKCaDGwf5-tGCCirFgw.png" /></figure><p>Voice User Interfaces, or VUIs, are audio, visual, and tactile interfaces that allow people to interact with devices using their voices. The presence of a visual interface is not required for a VUI.</p><p>Voice With smart assistants like Siri, Alexa, Google, and Cortana, user interface has achieved revolutionary success, with voice being the main mode of human communication. The future of user interface design is now, and it’s becoming better and better as machine learning capabilities expand with more engagement.</p><p>Voice technology is only the beginning; there is much more to this future of user interface that tech gurus have yet to uncover.</p><h4>4. Augmented Reality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*OQwrxcTZwjwWV5E76pEWnw.jpeg" /></figure><p>Augmented reality is no longer a cutting-edge concept. Companies have been exploiting the AR experience in a variety of applications, games, glasses, and systems, despite the fact that acceptance levels are still at an early stage. It has yet to reach its full potential, though.</p><p>AR uses computer-generated input to enrich the real-world environment and add perceptual simulated or virtual content, transforming the items around us into an interactive digital experience. It has made inroads into a variety of industries, including healthcare, retail, gaming, entertainment, hospitality, tourism, education, design, and so on.</p><h4>5. Virtual Reality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRBHKTWJAwhsKJI9K8qH9A.jpeg" /></figure><p>Virtual reality, or VR, is a seasoned technological player, but it has risen to new heights in recent years with the launch of VR headsets.</p><p>Virtual Reality creates a three-dimensional artificial world that can be explored and interacted with, providing a unique experience. The virtual environment is designed to give the user the impression that they are in a genuine place.</p><p>Virtual reality’s potential to provide immersive and entertaining experiences is propelling it into new industries such as health, architecture, gaming, entertainment, hospitality, and the arts. It’s only that additional research and technological improvement are needed before a high-potential interface can have a significant influence on our daily lives.</p><h3>Next generation UI design tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4MO3T8VYmlJKLcVAUjdxw.jpeg" /></figure><p>Since the earliest version of Adobe Photoshop, which was designed for altering photographs rather than designing dynamic user interfaces, UI design tools have gone a long way. Adobe XD, Figma, and Sketch are among the latest technologies that have made our tasks easier and faster.</p><p>Future user interface tools will combine design and coding to provide designers and developers a more seamless experience. Our existing technologies assist us in creating abstract representations of web UIs rather than actual online UIs. Figma and Sketch mock-ups are separate from the original code.</p><p>Many designers nowadays are familiar with the fundamentals of HTML and CSS. Some hardliners create in code, but this isn’t practical for big projects; designers need to be able to swiftly test a proof of concept before committing to it.</p><p>Visual Studio Code, a solution that unifies code editing and development and allows engineers to create, test, and debug code in the same environment, is available to software developers. Designers, therefore, want a visual development environment that not only allows them to design but also generates production-ready code.</p><p>To produce design components, current technologies rely on proprietary programming models. These models aren’t as strong as CSS, and they don’t let designers see the auto-generated code that lies behind their design files — code that must be exported to HTML, CSS, or JavaScript at some point. It would be a lot easier if our tools supported HTML and CSS right out of the box.</p><p>CSS, for example, employs the box model, which calls for arranging HTML components on each page within a box with height, width, border, and padding defined in code. With its auto-layout tool, Figma gets close to achieving this goal. Developers would need to translate and export less if Figma adopted the box model, which is already used by most online UIs.</p><h3>Impact on everyday life</h3><p>When it comes to technological advancements, the future is certainly exciting, and in many respects, the future has already arrived! Here, we’ll look at some examples of how future UI design will affect our daily lives.</p><h4>Room Alive</h4><p>RoomAlive is the follow-up to Microsoft Research’s IllumiRoom, which debuted at CES 2012. Both are steps toward a Kinect future in which “this is our house right now.” By layering input-output pixels on top of everything in the room, the new method goes beyond projection mapping around a TV. RoomAlive overlays an interactive screen from which there is no escape using several depth cameras and spatially mapped projectors.</p><p>Consider “real-life” video games that turn your living room into the game’s universe. Imagine virtual home décor, where you may project your image of how you wish to rearrange or add to the decor of your house.</p><h4>Skin Buttons</h4><p>Miniature projectors are used in the Skin Buttons project to show interactive symbols on the skin around the watch face. This technique allows a smartwatch’s interaction zone to grow without physically expanding it. The projector parts are less than $2 and can even extend the life of the battery by moving the effort away from the primary display.</p><h4>Flexsense</h4><p>The FlexSense is a translucent sheet of plastic with inbuilt piezoelectric sensors that sense the form in which it is placed. This enables a wide range of natural, paper-like interactions. Toggling layers in maps or drawings, for example, flipping up a corner to expose something underlying.</p><p>Consider phone cases that respond when the cover is peeled back. Alternatively, interactive books are children’s books that react as the page is turned.</p><p>Thank You.</p><h4>Ref:</h4><p><a href="https://www.quickreviewer.com/what-is-the-future-of-user-interface-ui-design/">The future of User Interface Design (UI) - QuickReviewer</a></p><p><a href="https://www.getwrecked.com/the-future-of-ui-design-and-how-it-will-impact-our-everday-lives/">https://www.getwrecked.com/the-future-of-ui-design-and-how-it-will-impact-our-everday-lives/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff16c895152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Cloud Functions Part 1]]></title>
            <link>https://hasitha-chandula.medium.com/firebase-cloud-functions-part-1-40d9fbd8d8e9?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/40d9fbd8d8e9</guid>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 17:52:32 GMT</pubDate>
            <atom:updated>2020-12-17T17:52:32.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgy9tD1ixcaztpirUw0QCw.png" /></figure><p>If you are using serverless to build your backend probably you heard about Firebase cloud functions. firebase provide us to a very easy way to build and deploy our backend using Nodejs using javascript or typescript. In this article, I’m going to show you what are the different function types we can use in firebase to build our backends easily.</p><h3>Pre-Requirements</h3><p>firebase account, Nodejs Installed on your computer, Firebase tools install as global using node js</p><h3>Types fo Firebase Cloud Functions</h3><p>Normal Functions (REST Apis)</p><p>Authentication Triggers (Trigger when new user signup using firebase authentication)</p><p>Storage Triggers (Trigger when storage updates)</p><p>Firestore Triggers (Trigger when firestore updates)</p><p>Realtime Database Triggers (Trigger when realtime database updates)</p><p>Pubsub (Background Functions)</p><h3><strong>Create a Firebase Project</strong></h3><p>Create a Firebase Project using firebase console by navigating <a href="https://console.firebase.google.com/">https://console.firebase.google.com/</a> and update your project to Pay as you go</p><h3><strong>Create Function Project</strong></h3><p>Create a Firebase function project using firebase CLI</p><p>Open terminal and type <strong><em>npm i -g firebase-tools</em></strong></p><p>Then in the project folder open terminal again and type <strong><em>firebase init functions</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQ6JJXWro8JlMiEf7zmQMA.png" /></figure><p>You’ll see this options list select User an existing project and select the project that you create using firebase console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTXvgAz6aerad1YExRG_yQ.png" /></figure><p>Then you’ll see this to select the language Javascript or Typescript, in this case, I’m using Typescript. And in next they ask to <strong>Do you want to use ESLint to catch probable bugs and enforce style? Y </strong>and enter</p><p><strong>Do you want to install dependencies with npm now? </strong>to this, I’m using N because I’m going to use Yarn, not npm. If you don’t install yarn to your computer you should type<strong> Y </strong>and enter.</p><p>Not Our project is created successfully.</p><h3><strong>Normal Cloud Function Implementation</strong></h3><p>Now open your project folder using a text editor in this case I’m using VsCode. (Open your text editor inside functions folder)</p><p>inside functions folder, we can see index.ts file (If you use javascript you’ll see index.js file)</p><p>Inside the index file, there is simple boilerplate code, we are going to deploy this code and see how this works.</p><pre>import * <em>as</em> functions from &quot;firebase-functions&quot;;</pre><pre><em>export</em> <em>const</em> helloWorld = functions.https.onRequest((_request, response) =&gt; {</pre><pre>functions.logger.info(&quot;Hello logs!&quot;, { structuredData: true });</pre><pre>response.status(200).json(&quot;Hello from Firebase!&quot;);</pre><pre>});</pre><p>In here helloWorld is the function name and after we deploy our function we can access these functions using URL/helloWorld.</p><p>To deploy this function open your terminal inside functions folder and type</p><p><strong><em>npm run deploy</em></strong> or <strong><em>yarn run deploy</em></strong></p><p>Once all done you’ll see this message with your endpoint url</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNntcFS6Xo6Fu6AeG6Robg.png" /></figure><p>copy that function URL and open postmen and send a get request, you’ll see some message like bellow,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLajwEv9RYj98yNF_sTh_A.png" /></figure><p>If you see this message congratulation you are successfully deploying your firebase cloud function. this is a simple response but you can be using services inside this function like you do in severs. this is the normal REST function using firebase cloud functions.</p><h3><strong>Authentication Triggers</strong></h3><p>Another type of firebase cloud function, we can trigger a function when new user signup using firebase authentication. these functions run as a background function, using this function we can add a newly created user to our database or otherthings like send and welcome email etc.</p><p>To test these functions first we need to go to the firebase console and enable firebase authentication via email and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gV2VjIwSOFqM5f1vtLQ7Q.png" /></figure><p>Once this was done we can do the implementation part.</p><pre>import * <em>as</em> functions from &quot;firebase-functions&quot;;</pre><pre>import * <em>as</em> admin from &quot;firebase-admin&quot;;</pre><pre>import { UserRecord } from &quot;firebase-functions/lib/providers/auth&quot;;</pre><pre>admin.initializeApp(functions.config().firebase);</pre><pre><em><br>export</em> <em>const</em> userCreate = functions.auth.user()</pre><pre>.onCreate(<em>async</em> (user: UserRecord) =&gt; {</pre><pre>functions.logger.info({</pre><pre>message: &quot;Newly Created User Details&quot;,</pre><pre>user},{ structuredData: true });</pre><pre>});</pre><pre><em>export</em> <em>const</em> userDelete = functions.auth.user()</pre><pre>.onDelete(<em>async</em> (user: UserRecord) =&gt; {</pre><pre>functions.logger.info({</pre><pre>message: &quot;Newly Created User Details&quot;,</pre><pre>user,</pre><pre>},{ structuredData: true });</pre><pre>});</pre><p>In here I have created two cloud function one is trigger when a user was added and another one is trigger when a user was deleted. I have added firebase logs then we can see if these functions trigger correctly.</p><p>once again we need ti to deploy our functions using</p><p><strong><em>npm run deploy or yarn run deploy</em></strong></p><p>once all done go to the firebase console and authentication section add new user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FMV-rP6sbv2BZagZszllA.png" /></figure><p>Once new user added go to the functions logs section and filter userCreate function and you can see the message like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm0_0Jpl8dF8EX_UKovO9A.png" /></figure><p>this means our authentication trigger function is successful.</p><p>Now we test userDelete Trigger function to do that we need to go to the authentication section and delete one user and see logs in deleteUserLogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTSIrEMd4qHmhf3Ju2zDyA.png" /></figure><p>If you see logs like this your deleteUser function is successful.</p><p>Now we Build the Normal cloud function and Authentication triggers.</p><p>Here is the full code.</p><pre>import * <em>as</em> functions from &quot;firebase-functions&quot;;</pre><pre>import * <em>as</em> admin from &quot;firebase-admin&quot;;</pre><pre>import { UserRecord } from &quot;firebase-functions/lib/providers/auth&quot;;</pre><pre>admin.initializeApp(functions.config().firebase);</pre><pre><em>export</em> <em>const</em> userCreate = functions.auth.user()</pre><pre>.onCreate(<em>async</em> (user: UserRecord) =&gt; {<br>functions.logger.info({<br>message: &quot;Newly Created User Details&quot;,<br>user},{ structuredData: true })<br>});</pre><pre><em>export</em> <em>const</em> userDelete = functions.auth.user().onDelete(<em>async</em> (user: UserRecord) =&gt; {</pre><pre>functions.logger.info({</pre><pre>message: &quot;Newly Created User Details&quot;,</pre><pre>user},<br>{ structuredData: true });</pre><pre>});</pre><pre><em>export</em> <em>const</em> helloWorld = functions.https.onRequest((_request, response) =&gt; {</pre><pre>functions.logger.info(&quot;Hello logs!&quot;, { structuredData: true });</pre><pre>response.status(200).json(&quot;Hello from Firebase!&quot;)<br>});</pre><p>In the next part, I’m going to implement Storage triggers, Realtime database triggers and Pubsub (Background Functions)</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40d9fbd8d8e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Licenses]]></title>
            <link>https://hasitha-chandula.medium.com/software-licenses-c0a0948ba6fa?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0a0948ba6fa</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-license]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 02:54:13 GMT</pubDate>
            <atom:updated>2020-09-08T11:47:47.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IeVIyBNGzUfBDY2jSORd5g.jpeg" /></figure><p>A software license is a document that provides legally binding guidelines for the use and distribution of software.</p><p>Software licenses typically provide end-users with the right to one or more copies of the software without violating copyrights. The license also defines the responsibilities of the parties entering into the license agreement and may impose restrictions on how the software can be used. Software licensing terms and conditions usually include fair use of the software, the limitations of liability, warranties, and disclaimers, and protections if the software or its use infringes on the intellectual property rights of others.</p><p>Software licenses typically are either proprietary, free or open-source, the distinguishing feature being the terms under which users may redistribute or copy the software for future development or use.</p><p>There are many different types of software licenses, and the penalties for license non-compliance can be harsh. If you reuse a component without following the obligations of its license, the licensor might sue, and you might be forced to publish your own source code. To protect your code and your organization, you need to understand these software licenses before using any code, including libraries and frameworks, you didn’t write yourself. See our list of the top open-source licenses and their potential legal risks.</p><h3>What are the different types of software licenses?</h3><p>Here are five types of common software license models you should know about. Four are examples of open source licenses (which allow you to reuse code to some extent), and one disallows any reuse whatsoever.</p><h3>Public domain.</h3><p>This is the most permissive type of software license. When software is in the public domain, anyone can modify and use the software without any restrictions. But you should always make sure it’s secure before adding it to your own codebase. Warning: Code that doesn’t have an explicit license is NOT automatically in the public domain. This includes code snippets you find on the internet.</p><h3>Permissive.</h3><p>Permissive License is also known as “Apache-style” or “BSD style.” They contain minimal requirements about how the software can be modified or redistributed. This type of software license is perhaps the most popular license used with free and open-source software. Aside from the <a href="https://www.apache.org/licenses/LICENSE-2.0">A</a>pache License and the BSD License, another common variant is the MIT License.</p><h3>LGPL.</h3><p>The GNU Lesser General Public License allows you to link to open source libraries in your software. If you simply compile or link an LGPL-licensed library with your own code, you can release your application under any license you want, even a proprietary license. But if you modify the library or copy parts of it into your code, you’ll have to release your application under similar terms as the LGPL.</p><h3>Copyleft.</h3><p>Copyleft licenses are also known as reciprocal licenses or restrictive licenses. The most well-known example of a copyleft or reciprocal license is the GPL. These licenses allow you to modify the licensed code and distribute new works based on it, <em>as long as</em> you distribute any new works or adaptations under the same software license. For example, a component’s license might say the work is free to use and distribute for personal use only. So any derivative you create would also be limited to personal use only. (A derivative is any new software you develop that contains the component.)</p><p>The catch here is that the users of your software would also have the right to modify the code. Therefore, you’d have to make your own source code available. But of course, exposing your source code may not be in your best interests.</p><h3>Proprietary.</h3><p>Of all types of software licenses, this is the most restrictive. The idea behind it is that all rights are reserved. It’s generally used for proprietary software where the work may not be modified or redistributed.</p><h3>Examples of software licenses</h3><ul><li><strong>Single-user license</strong> — The software is licensed for a single user and often a single computer.</li><li><strong>Multi-user license</strong> — This license allows you to install a program onto multiple computers used by multiple users. Typically this may be a set number of users. For example, a five-user multi-user license allows up to five people to use the program.</li><li><strong>Site license</strong> — A program can be installed on an unlimited amount of computers, as long as they’re at the location of the site license. Site licenses are usually for schools and businesses.</li></ul><h3>How do I know what licenses apply to the code in my codebase?</h3><p>Before you can determine which licenses govern any reused code in your codebase, you need to create a software bill of materials or a list of all the components in your code. And the fastest way to generate that list is with a software composition analysis tool. A good SCA tool will be able to find full components as well as code snippets, and it’ll tell you which licenses apply to each piece of code and whether you might be using licenses that have conflicts.</p><h3>Are software licenses transferrable?</h3><p>In most situations, a retail version of an operating system license and software license is transferrable as long as it isn’t used on the older computer. For example, a retail version of Microsoft Windows can be transferred to another computer as long as the other computer is no longer used or switched its operating system</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0a0948ba6fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Whistleblowing?]]></title>
            <link>https://hasitha-chandula.medium.com/what-is-whistleblowing-e91439579c0e?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91439579c0e</guid>
            <category><![CDATA[whistleblower]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 15:17:01 GMT</pubDate>
            <atom:updated>2020-07-25T15:17:01.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOGJG9utVJ9CUOHoCfG_IA.jpeg" /></figure><p>A whistleblower could be any form of a person or from any form of profession. They could be an employee, supplier, or contractor of a company or government institution who opts to disclose information to the public regarding wrongdoings of the institution. Such wrongdoings maybe corruption, fraud, or any other malicious activity which causes harm to the public.</p><p>A whistleblower has the characteristics of sharing their perspective on any wrongdoing happening in the company or within a specific department of the company. There are laws to protect whistleblowers from losing their job or getting mistreated. There is a process for a whistleblower to take legal action in order to report the fraud of an organization. They can file a lawsuit or make a complaint to the relevant authorities in order to evoke a criminal investigation.</p><p>Whistleblowers are of two types:</p><h3><strong>External Whistleblower</strong></h3><p>They will directly enlighten the people outside the organization. Mostly they will approach the media, police, or relevant law keepers.</p><h3><strong>Internal whistleblower</strong></h3><p>They will report the frauds to the senior officers or administrators within the hierarchy of the organization.</p><h3><strong>Elements of Ethical Whistleblowing</strong></h3><ol><li>Understand the whistleblowing law</li></ol><p>The disclosures of the employee must fall into the category of whistleblowing law. Just a collection of random confidential information and threatening would not be sufficient. The information gathered must fall into one or more of the below-mentioned categories; criminal offenses, breach of any legal obligation, miscarriages of justice, danger to the health and safety of personnel, damage to the environment, or deliberate concealing of information.</p><p>2. Introduction of a whistleblowing policy</p><p>Government bodies registered private organizations and other authorized and legal institutions have the obligation to adopt an accepted whistleblowing policy. The recommendation is that employees or potential whistleblowers must report to the internal hierarchy of the organization instead of reporting to outsiders.</p><p>3. Protection of the whistleblower</p><p>Whistleblowers must be given the guarantee that no threats or adverse consequences such as harassment or revenge would not take in the aftermath of a whistleblowing incident.</p><p>4. Respond to allegations of wrongdoing</p><p>Assurance must be given to workers that the disclosures will be written down in meetings to avoid misunderstandings. A team of officers should be appointed in order to handle this process.</p><p>5. Be prepared of cases escalating to an employment tribunal</p><p>A potential whistleblower can bring claims against individual employees or employers to the tribunal. Employees can apply for “interim relief” which allows them to have their payroll until the outcome of the tribunal.</p><h3><strong>Steps for Whistleblowing</strong></h3><ol><li>Collect the evidence</li></ol><p>The whistleblower must ensure that they possess the right evidence. Evidence of unclear means and evidence collected based on assumptions might bring on adverse consequences for the whistleblower. Ensure the proofs, documents, footage are well organized and are of proper disclosure material.</p><p>2. Lodge the complaint</p><p>Follow the correct process in lodging the complaint and submit it to the relevant authorities. Disclosures statements and evidence of the misconduct must also be provided simultaneously.</p><p>3. Acquire services of legal advisers</p><p>Acquiring the services of an experienced lawyer who has dealt with whistleblowing cases is of vital importance. It is always advantageous to have personnel by the side who knows the legal aspect of such cases.</p><p>4. Prepared to be testified</p><p>Do not be surprised if the whistleblower is brought ahead to be testified. Such scenarios are often a possibility. In such cases, the whistleblower must be prepared to reveal the accurate findings of the misconduct.</p><p>5. Prepared to face the consequence</p><p>There are always consequences in whistleblowing cases. The whistleblower may be dismissed from the company or may have to face threats. On such occasions it is always safe to seek the help of the law and the law enforcement authorities.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91439579c0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST  API  with  Deno]]></title>
            <link>https://medium.com/analytics-vidhya/rest-api-with-deno-1e23b5bad1bd?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e23b5bad1bd</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[deno]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Tue, 17 Mar 2020 03:17:25 GMT</pubDate>
            <atom:updated>2020-05-17T17:12:16.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>REST API with Deno</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUK98koeh35lz7kz13RIgg.jpeg" /></figure><h3>What is Deno, and what are its main features?</h3><p><strong>Deno</strong> is a runtime for JavaScript and TypeScript that is based on the V8 JavaScript engine and the Rust programming language. It was created by <strong>Ryan Dahl</strong>, the original creator of Node. js, and is focused on security and productivity.</p><p>It was built with:</p><ul><li>Rust (Deno’s core was written in Rust, Node’s in C++)</li><li>Tokio (the event loop written in Rust)</li><li>TypeScript (Deno supports both JavaScript and TypeScript out of the box)</li><li>V8 (Google’s JavaScript runtime used in Chrome and Node, among others)</li></ul><p>Still, Deno is under development and it has lots of bugs. But we can build simple REST API Using Deno. And also there are no node_modules in the Deno project.</p><p>Here I’m going to show you how to build a simple REST API with CRUD operations with Deno. I&#39;m Not going to use any database and all data store in JSON file.</p><p>First of all, we need to install Deno on our computer. you can do that by referring <a href="https://deno.land/">https://deno.land/</a> according to your operating system.</p><p>In windows open the power shell and copy and paste this</p><p>iwr https://deno.land/x/install/install.ps1 -useb | iex</p><p>command and press enter (it will take some time )</p><h3>Folder and files Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*cu4zn25EsKtwHZeaAg8c_Q.png" /></figure><p>Since there is no node_modules in Deno we need to import Libraries and dependencies from the internet.</p><p>Let&#39;s build our REST API (Ignore red underlines in screenshots, I did not install Deno extensions in vs code)</p><p>First, we create our main file (index.ts)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*WSa4DZFYr7grCgnHjIfs1g.png" /></figure><pre>// oak is pretty much similar to express in nodejs<br>import { Application } from “https://deno.land/x/oak/mod.ts&quot;;</pre><pre>// Import App host and Port from config file<br>import { APP_HOST, APP_PORT } from “./config/config.ts”;</pre><pre>// Import router from routes file<br>import router from ‘./routes/routes.ts’;</pre><pre><em>// Create Application Like Express<br></em>const app = new Application()</pre><pre><em>// Add Routes<br></em>app.use(router.routes())<br>app.use(router.allowedMethods())</pre><pre><em>// Display App running<br></em>console.log(`App Started at Port ${APP_PORT}`)</pre><pre>await app.listen(`${APP_HOST}:${APP_PORT}`)</pre><p><strong>config/config.ts </strong>file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*LFqQb77zuWgNYCZZlhDmKg.png" /></figure><pre>const env = Deno.env();</pre><pre>export const APP_HOST = env.APP_HOST || &quot;127.0.0.1&quot;;</pre><pre>export const APP_PORT = env.APP_PORT || 5000;</pre><pre>export const DB_PATH = env.DB_PATH || &quot;./db/todos.json&quot;;</pre><p><strong>models/todos.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*oIJr7LoNVmPdSZQnQpEFRQ.png" /></figure><pre>export default interface ToDos {</pre><pre>   id: string;</pre><pre>   title: string;</pre><pre>   description: string;</pre><pre>}</pre><p><strong>routes/routes.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*6gSnzA-6ldxqfuJ2miZY0g.png" /></figure><pre>import { Router } from &quot;https://deno.land/x/oak/mod.ts&quot;;</pre><pre>import getTodos from &#39;./todos/getTodos.ts&#39;;</pre><pre>import getTodo from &#39;./todos/getTodo.ts&#39;;</pre><pre>import addTodo from &#39;./todos/addTodos.ts&#39;;</pre><pre>import deleteTodo from &#39;./todos/deleteTodo.ts&#39;;</pre><pre>import editTodo from &#39;./todos/editTodo.ts&#39;;<br></pre><pre>const router = new Router()</pre><pre>router.get(&#39;/todos&#39;, getTodos)<br></pre><pre>router.get(&#39;/todo/:id&#39;, getTodo)</pre><pre>router.post(&#39;/addTodo&#39;, addTodo)</pre><pre>router.put(&#39;/editTodo/:id&#39;, editTodo)</pre><pre>router.delete(&#39;/deleteTodo/:id&#39;, deleteTodo)</pre><pre>export default router;</pre><p><strong>db/todos.json </strong>file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*lWnO6Oekv7aDqYa0co0BSA.png" /></figure><pre>[</pre><pre>{</pre><pre>&quot;id&quot;:&quot;010fbf79-048e-4508-ac65-5c8b326aa026&quot;,</pre><pre>&quot;title&quot;:&quot;Learn TypeScript&quot;,</pre><pre>&quot;description&quot;:&quot;TypeScript is typed version of JavaScript&quot;</pre><pre>},</pre><pre>{</pre><pre>&quot;id&quot;:&quot;38bd9aad-4047-47e1-b879-7a9ab77761c5&quot;,</pre><pre>&quot;title&quot;:&quot;Learn React&quot;,</pre><pre>&quot;description&quot;:&quot;React is a Front-End web Library&quot;</pre><pre>},</pre><pre>{</pre><pre>&quot;id&quot;:&quot;81ded252-661c-4fb1-a1e0-aad717b84891&quot;,</pre><pre>&quot;title&quot;:&quot;Learn Deno&quot;,</pre><pre>&quot;description&quot;:&quot;Deno is the next version of nodejs&quot;</pre><pre>}</pre><pre>]</pre><p><strong>db/db.ts</strong> (Where we add and get data from todos.json file) file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pym3JbunOfWqKN9Wts5XLw.png" /></figure><pre>import { DB_PATH } from &#39;../config/config.ts&#39;;</pre><pre>import ToDos from &#39;../models/todos.ts&#39;;</pre><pre>export const getTodosFromJson: () =&gt; Promise&lt;ToDos[]&gt; = async () =&gt;{</pre><pre>try {</pre><pre><em>// Read Files In Deno<br></em>const data: any = await Deno.readFile(DB_PATH);</pre><pre><em>// Decode Data From File<br></em>const decode = new TextDecoder()</pre><pre>const decodedData = decode.decode(data)</pre><pre>return JSON.parse(decodedData)</pre><pre>} catch (err) {</pre><pre>console.error(err.message);</pre><pre>}</pre><pre>}</pre><pre>export const writeDataToJson: (<em>todos</em>: ToDos[]) =&gt; Promise&lt;void&gt; = async (<em>todos</em>: ToDos[]): Promise&lt;void&gt; =&gt; {</pre><pre>try {</pre><pre><em>// encode Json</em></pre><pre>const encode = new TextEncoder();</pre><pre><em>// Write Files in Deno</em></pre><pre>await Deno.writeFile(DB_PATH, encode.encode(JSON.stringify(<em>todos</em>)))</pre><pre>} catch (err) {</pre><pre>console.error(err.message);</pre><pre>}</pre><pre>}</pre><p><strong>routes/todos/getTodos.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*TOQDMmslxCPC2VOZJ2liAw.png" /></figure><pre>import { Response } from &quot;https://deno.land/x/oak/mod.ts&quot;;</pre><pre>import ToDos from &#39;../../models/todos.ts&#39;;</pre><pre>import id from &#39;../../services/createIds.ts&#39;</pre><pre>import { getTodosFromJson } from &#39;../../db/db.ts&#39;;</pre><pre>const getTodos = async ({ <em>response</em> }: { response: Response }) =&gt; {</pre><pre>try {</pre><pre>const todos: ToDos[] = await getTodosFromJson()</pre><pre>response.body = todos;</pre><pre>} catch (err) {</pre><pre>console.error(err.message);</pre><pre>}</pre><pre>}</pre><pre>export default getTodos</pre><p><strong>routes/todos/getTodo.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZQRvT2zuWwPiN5HcXq1JQ.png" /></figure><pre>import { Response } from &quot;https://deno.land/x/oak/mod.ts&quot;;</pre><pre>import { getTodosFromJson } from &#39;../../db/db.ts&#39;;</pre><pre>const getTodo = async ({ <em>params</em>, <em>response</em> }: { params: any, response: Response }) =&gt; {</pre><pre>const id = params?.id</pre><pre>if (!id) {</pre><pre>response.status = 400;</pre><pre>response.body = { msg: &#39;Invalid Id&#39; }</pre><pre>}</pre><pre>const todos = await getTodosFromJson()</pre><pre>const todo = todos.find(<em>todo</em> =&gt; <em>todo</em>.id === id)</pre><pre>if (!todo) {</pre><pre>response.status = 404;</pre><pre>response.body = { msg: `No Todo Found on ${id}` }</pre><pre>return;</pre><pre>}</pre><pre>response.status = 200;</pre><pre>response.body = todo;</pre><pre>}</pre><pre>export default getTodo</pre><p><strong>routes/todos/addTodos.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QvHRMp4VZdMshL-Rz4WDVQ.png" /></figure><pre>import { Request, Response } from &quot;https://deno.land/x/oak/mod.ts&quot;;</pre><pre>import { v4 as uuid } from &quot;https://deno.land/std/uuid/mod.ts&quot;;</pre><pre>import ToDos from &#39;../../models/todos.ts&#39;;</pre><pre>import { writeDataToJson, getTodosFromJson } from &#39;../../db/db.ts&#39;;</pre><pre>const addTodo = async ({ <em>request</em>, <em>response</em> }: { request: Request, response: Response }) =&gt; {</pre><pre><em>// Check Request Has a body or not</em></pre><pre>if (!request.hasBody) {</pre><pre>response.status = 400;</pre><pre>response.body = { msg: &quot;Invalid data, Please Add Title and Description&quot; };</pre><pre>return;</pre><pre>}</pre><pre><em>// Get Title and description from Request</em></pre><pre>const {</pre><pre>value: { title, description }</pre><pre>} = await request.body();</pre><pre><em>// Check title and description is valid</em></pre><pre>if (!title || !description) {</pre><pre>response.status = 422;</pre><pre>response.body = { msg: &quot;Title and Description is required&quot; };</pre><pre>return;</pre><pre>}</pre><pre><em>// Create New Todo</em></pre><pre>const newTodo: ToDos = { id: uuid.generate(), title, description }</pre><pre><em>// Get All Todos</em></pre><pre>let allTodos: ToDos[] = await getTodosFromJson()</pre><pre><em>// Add New Todo to allTodos Array</em></pre><pre>allTodos = [newTodo, ...allTodos]</pre><pre><em>// Save Data In ToDos.json File</em></pre><pre>await writeDataToJson(allTodos)</pre><pre><em>// Response To the Client</em></pre><pre>response.body = { msg: &quot;New Todo Created&quot;, newTodo };</pre><pre>};</pre><pre>export default addTodo</pre><p><strong>routes/todos/editTodo.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnj1NP9D4sQ_KADcG6ihOg.png" /></figure><pre>import { Response, Request } from &quot;https://deno.land/x/oak/mod.ts&quot;;</pre><pre>import { getTodosFromJson, writeDataToJson } from &#39;../../db/db.ts&#39;;</pre><pre>import ToDos from &#39;../../models/todos.ts&#39;;</pre><pre>const editTodo = async ({ <em>params</em>, <em>request</em>, <em>response</em> }: { params: any, request: Request, response: Response }): Promise&lt;void&gt; =&gt; {</pre><pre>try {</pre><pre><em>// Save todo id to a variable</em></pre><pre>const id = params.id;</pre><pre><em>// Check Request Has a body or not</em></pre><pre>if (!request.hasBody) {</pre><pre>response.status = 400;</pre><pre>response.body = { msg: &quot;Invalid data, Please Add Title and Description&quot; };</pre><pre>return;</pre><pre>}</pre><pre><em>// Get Title and description from Request</em></pre><pre>const {</pre><pre>value: { title, description }</pre><pre>} = await request.body();</pre><pre><em>// Check title and description is valid</em></pre><pre>if (!title || !description) {</pre><pre>response.status = 422;</pre><pre>response.body = { msg: &quot;Title and Description is required&quot; };</pre><pre>return;</pre><pre>}</pre><pre><em>// Get All Todos From Json File And Save it in to a Variable</em></pre><pre>let allTodos: ToDos[] = await getTodosFromJson();</pre><pre><em>// Check if todo is here in that Id sent by client</em></pre><pre>const todo: ToDos | undefined = allTodos.find((<em>todo</em>: ToDos) =&gt; <em>todo</em>.id === id)</pre><pre><em>// check todo is undefined, if so then response 404</em></pre><pre>if (!todo) {</pre><pre>response.status = 404;</pre><pre>response.body = { msg: `No Todo Found on this ${id} id` }</pre><pre>return;</pre><pre>}</pre><pre><em>//    Add New Title And Description to Old One</em></pre><pre>todo.title = title;</pre><pre>todo.description = description;</pre><pre>await writeDataToJson(allTodos)</pre><pre>response.status = 200;</pre><pre>response.body = { msg: &quot;Todo has been Edited&quot;, todo }</pre><pre>} catch (err) {</pre><pre>console.error(err.message);</pre><pre>}</pre><pre>}</pre><pre>export default editTodo;</pre><p><strong>routes/todos/deleteTodo.ts</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnj1NP9D4sQ_KADcG6ihOg.png" /></figure><pre>import { Response } from &quot;https://deno.land/x/oak/mod.ts&quot;;</pre><pre>import { getTodosFromJson, writeDataToJson } from &#39;../../db/db.ts&#39;;</pre><pre>import ToDos from &#39;../../models/todos.ts&#39;;</pre><pre>const deleteTodo = async ({ <em>params</em>, <em>response</em> }: { params: any, response: Response }): Promise&lt;void&gt; =&gt; {</pre><pre>try {</pre><pre><em>// Save todo id to a variable</em></pre><pre>const id = params.id;</pre><pre><em>// Get All Todos From Json File And Save it in to a Variable</em></pre><pre>let allTodos = await getTodosFromJson();</pre><pre><em>// Check if todo is here in that Id sent by client</em></pre><pre>const index = allTodos.findIndex((<em>todo</em>: ToDos) =&gt; <em>todo</em>.id === id)</pre><pre><em>// if todo is here index &gt; 0</em></pre><pre><em>// if todo is not here index = -1</em></pre><pre><em>// check index &lt; 0, if so then response 404</em></pre><pre>if (index &lt; 0) {</pre><pre>response.status = 404;</pre><pre>response.body = { msg: `No Todo Found on this ${id} id` }</pre><pre>return;</pre><pre>}</pre><pre><em>// if index &gt; 0 then filter the array and delete todo and save</em></pre><pre>allTodos = allTodos.filter((<em>todo</em>: ToDos) =&gt; <em>todo</em>.id !== id)</pre><pre>await writeDataToJson(allTodos)</pre><pre>response.status = 200;</pre><pre>response.body = { msg: &quot;Todo has been Deleted&quot; }</pre><pre>} catch (err) {</pre><pre>console.error(err.message);</pre><pre>}</pre><pre>}</pre><pre>export default deleteTodo;</pre><p>Now Our Simple REST API if finished. to run server all we need to do is open the cmd or terminal in that project folder and run</p><h3><strong>deno run --allow-all index.ts</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*QRs9Cvsr1e1NlkvKidgU0w.png" /></figure><p>yot will get a message like this. now You can test your REST API using a tool like postman.</p><p>Github repo:- <a href="https://github.com/Hasi6/REST-API-Using-Deno">https://github.com/Hasi6/REST-API-Using-Deno</a></p><p>That’s it Happy Coding. Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e23b5bad1bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/rest-api-with-deno-1e23b5bad1bd">REST  API  with  Deno</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YouTube Video Downloader ( Python )]]></title>
            <link>https://medium.com/analytics-vidhya/youtube-video-downloader-python-c1f449e758ff?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f449e758ff</guid>
            <category><![CDATA[pytube]]></category>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Sat, 18 Jan 2020 15:50:04 GMT</pubDate>
            <atom:updated>2020-01-19T05:14:10.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>YouTube Video Downloader(Python)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*jAtMRN4rWsR2cOyp0XsOKA.jpeg" /></figure><p>In this tutorial, I’m going to show you build your own Youtube video downloader using python (cmd app). And this is a very fun project.</p><p>To start with this project first you need to install python3 in your computer and also a text editor or IDE ( vs code, pycharm ). To build this app we use pytube library. you can check this library<a href="https://pypi.org/project/pytube/"> here</a>. To install this library open your cmd and type and press <strong><em>pip install pytube. </em></strong>And also we are using virtualenv here so we need to install that too. <strong><em>pip inatall virtualenv</em></strong></p><p>Now Environment setup is done. Now coding part. As an IDE I’m using vs code. Now go to your project folder and open cmd and type <strong><em>virtualenv venv. </em></strong>It will create a virtual environment to build our application. And we need to activate our virtual env. if your computer Linux or mac you can activate by typing <strong><em>source ./venv/bin/activate </em></strong>and if you are a windows<strong><em> </em></strong>user you can activate <strong><em>source ./venv/scripts/activate </em></strong>and press Enter.</p><p>Now open your project using vs code and create index.py file. And code look like this.</p><pre>from pytube import YouTube</pre><pre>#<em> Youtube video link you need to download<br></em>yt = YouTube(&quot;https://www.youtube.com/watch?v=anq3D5XFFew&quot;)  </pre><pre>#<em> Display all formats this video available<br></em>print(yt.streams.all())</pre><p>To run the file in cmd type and Press Enter <strong><em>python index.py. </em></strong>If you are seeing something like bellow you are good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_4Zg2k9aiQEhtQdhoO8Jg.png" /><figcaption>result</figcaption></figure><p>But sometimes it gives errors. In that error, there is a line <strong><em>mixins.py </em></strong>copy that path and open that file. we need to modify that file. Delete all code lines in that file and paste bellow lines of codes and save.</p><p><a href="https://github.com/nficano/pytube/blob/e5f1a9e2476b096ed2012939d50851d3499016e1/pytube/mixins.py">Code is here</a>.</p><p>And run again now all errors are gone.</p><p>As a result, you can see the itag in every Stream. It means the quality of the video. using this itag we can download videos.</p><pre>from pytube import YouTube</pre><pre>yt = YouTube(&quot;https://www.youtube.com/watch?v=anq3D5XFFew&quot;) <br>#<em> Youtube video link you need to download</em></pre><pre>#<em> Display all formats this video available</em>print(yt.streams.all())</pre><pre>#<em> Download Video<br></em>yt.streams.get_by_itag(22).download()</pre><p>Now run the file again. now you can see video file in your project directly.</p><p>Now you can modify this as you want. As an example, if we want to download more than one file we can use a list and for loop, code looks like this.</p><pre>from pytube import YouTube</pre><pre># List of video links<br>video_list = [&quot;https://www.youtube.com/watch?v=XjKGJf2X-U8&amp;list=TLPQMTcwMTIwMjBHNRzgUhODbQ&amp;index=1&quot;,&quot;https://www.youtube.com/watch?v=Dq-SpbVX8gc&amp;list=TLPQMTcwMTIwMjBHNRzgUhODbQ&amp;index=2&quot;,&quot;https://www.youtube.com/watch?v=anq3D5XFFew&quot;]</pre><pre>for link in video_list:<br>    yt = YouTube(link)<br>    yt.streams.get_by_itag(22).download()<br>    print(yt.streams.get_by_itag(22))</pre><p>That&#39;s it. I hope you enjoy this small project.</p><p>Thank you and Enjoy Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f449e758ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/youtube-video-downloader-python-c1f449e758ff">YouTube Video Downloader ( Python )</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send Email with Gmail, Python, and Flask]]></title>
            <link>https://medium.com/analytics-vidhya/send-email-with-gmail-python-and-flask-1810c25cf5f5?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/1810c25cf5f5</guid>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Tue, 14 Jan 2020 04:44:45 GMT</pubDate>
            <atom:updated>2020-01-14T04:44:45.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*FVQi12ZncNnKT0i0mtIFsg.png" /></figure><p><strong>What you’ll need?</strong></p><ul><li>Python (I’m using Python 3.6.4)</li><li><a href="https://pypi.python.org/pypi/pip">Pip</a> for installing dependencies</li><li><a href="https://virtualenv.pypa.io/en/stable/">Virtualenv</a></li><li><a href="https://accounts.google.com/SignUp">A Gmail account</a> ( Without two-step verification and allow unsafe apps)</li></ul><p>First Go to your Project Folder and Open Terminal on that folder and type <strong><em>virtualenv venv </em></strong>and this will create a virtual environment to our project. Then we need to activate virtualenv, if you are using Mac or Linux you can activate by type <strong><em>source env/bin/activate </em></strong>in the terminal. If you are using windows type <strong><em>source env/scripts/activate.</em></strong></p><p>Then We need to install <strong><em>Flask-Mail.</em></strong></p><p>To do that in terminal type <strong><em>pip install Flask-Mail. </em></strong>After that, we can start coding.</p><pre>from flask import Flask, jsonify<br>from flask_mail import Mail, Message<br><br>app = Flask(__name__)<br><br>mail_settings = {<br>    &quot;MAIL_SERVER&quot;: &#39;smtp.gmail.com&#39;,<br>    &quot;MAIL_PORT&quot;: 465,<br>    &quot;MAIL_USE_TLS&quot;: False,<br>    &quot;MAIL_USE_SSL&quot;: True,<br>    &quot;MAIL_USERNAME&quot;: &#39;YOUR_GMAIL&#39;,<br>    &quot;MAIL_PASSWORD&quot;: &#39;YOUR_PASSWORD&#39;<br>}<br><br>app.config.update(mail_settings)<br>mail = Mail(app)</pre><pre>app.config.update(mail_settings)</pre><pre>mail = Mail(app)</pre><p>These are the configurations. Now what I’m going to do is when the user requests a Get request “/&lt;string: email&gt;” to this then we will email to users request email. Here is the code,</p><p>First, create a file app.py and paste this code and input your Gmail and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwVVQ-QSK8EFAXk_xPwclg.png" /></figure><p>then you need to run the app using <strong><em>python app.py</em></strong> in the terminal.</p><p>You can use postman to do Http requests and test the app.</p><p>That’s it. Enjoy Python.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1810c25cf5f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/send-email-with-gmail-python-and-flask-1810c25cf5f5">Send Email with Gmail, Python, and Flask</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Chat-App with React & Flask]]></title>
            <link>https://medium.com/analytics-vidhya/simple-chat-app-with-react-flask-b2ae72404fcb?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ae72404fcb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 14:47:35 GMT</pubDate>
            <atom:updated>2020-01-13T04:31:53.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*bRgJv0M4oZ0-4l_ftqrznw.jpeg" /></figure><p>In this article, I’m going to show you how to build a real-time simple chat app using react, flask and socket.Io libraries. React is JavaScript Library and Flask is python Library. I use React as my client-side and flask as my server-side. And I used socket.Io to make my app Real-Time.</p><p>First I’m Going To Build Server-Side part using flask.</p><p>First, you need to install python 3 on your computer or if you did not <a href="https://www.python.org/downloads/">click here</a> and download and install the latest version of python 3. After that, you need to install flask and virtualenv son your computer. You can do that by opening your terminal or cmd (windows) and types <strong><em>pip install flask virtualenv.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*VPmKyIwP8Sik9C-N5Za_8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KILgdDjjVWY9j560s5HCNQ.png" /><figcaption>I Already install before so it gives me a response like this</figcaption></figure><p>Then go to your project folder and create virtualenv. <strong><em>virtualenv venv.</em></strong></p><p>It will create a venv folder and it is your environment for this application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaW6EJ4TTDIDdWSdfVuyeg.png" /></figure><p>Now Open this folder your favourite text editor I’m Using vs-code and create a folder src. Inside src folder create app.py file. This app.py file is the main file in our application.</p><p>Then we need to activate our virtualenv to do that open terminal in your project folder and type <strong><em>source ./venv/scripts/activate.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*bXqTVp3uHZT18AN3PHmMTA.png" /><figcaption>Now in terminal (venv) shown</figcaption></figure><p>And Lastly, we need to install flask_socketio. We can do the using <strong><em>pip install flask_socketio</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDpwpI6tpviYJxXfBTjc6Q.png" /></figure><p>Now Environment setup is done in server-side. In app.py file first, we need to import flask and flask_socketio staff to build a server app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJyaKuO79o_sJOuyqEscyg.png" /><figcaption>Server-side code</figcaption></figure><p>Now Server-side is done and we need to run our server. Open terminal in our project <strong><em>src </em></strong>Folder and type python app.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyPx5og4uElgHSbQZkaMtg.png" /></figure><p>It will give a message like this. So in my case, my app will run port 5000. you can find your server port by terminal details like the above image. Now We need to work with a client-side.</p><p>Start with client-side with react first we need to install nodejs. <a href="https://nodejs.org/en/">Click here</a> and download and install nodejs on your computer. After that, we need to create react app using create-react-app. install it globally type <strong><em>npm i -g create-react-app. </em></strong>After install go to your project folder and open terminal and type <strong><em>create-react-app client.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*3pMllhlIijOjP1XpRCNd-w.png" /></figure><p>After app created open client folder in a text editor and inside App.js file paste bellow code ( Code explains in comments )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCSVcn06Lxp3sIPIhXArrQ.png" /></figure><p>Now the server and client-side done.</p><p>Now npm start in client folder and test your app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDq-SpbVX8gc%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDq-SpbVX8gc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDq-SpbVX8gc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9318a7c1bde1ab0210e47050881a8c05/href">https://medium.com/media/9318a7c1bde1ab0210e47050881a8c05/href</a></iframe><p><a href="https://github.com/Hasi6/React-Flask-Chat-App">Source code</a></p><p>That’s it. Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ae72404fcb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/simple-chat-app-with-react-flask-b2ae72404fcb">Simple Chat-App with React &amp; Flask</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RESTful API with Python and Flask]]></title>
            <link>https://medium.com/analytics-vidhya/restful-api-with-python-and-flask-6e65e79a5e15?source=rss-11df3e0b5159------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e65e79a5e15</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Hasitha Chandula]]></dc:creator>
            <pubDate>Sun, 29 Dec 2019 18:02:29 GMT</pubDate>
            <atom:updated>2020-01-02T14:19:50.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XzIRJGujfqAiOV2EIQgR_Q.png" /></figure><p>Python is one of the most popular Programming Language. There are many frameworks and libraries in python. Flask is one of them. In this article, I’m going to show you how to build a simple RESTful API using Flask.</p><p>Before start, you need to install python 3 on your computer. You can download and install python 3 by clicking <a href="https://www.python.org/downloads/">here</a>. After that, you can verify that by type python — version on your terminal or cmd in windows.</p><p>To build Flask App First we need to install Flask by type pip install flask in terminal and press enter. After flask installed successfully now we can build our RESTApi.</p><h3>Create Server</h3><p>First, we need to create a server using flask. To do that we need to create a new python file. I named it app.py and the code looks like bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f29oEkYjs5MQkvBf71z2Q.png" /></figure><p>In here what I did was import the Flask from flask and create our server in port 5000. Now we can access our server in <a href="http://localhost:5000.">http://localhost:5000.</a> Now in the project directory open the terminal and enter python app.py and press enter. Now if you see something like bellow we are good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNOPZwI-ITyAhnu3pdxCcg.png" /></figure><p>We can create routes using our app variable. I will show you how to create GET, POST, PUT, DELETE routes.</p><h3>GET Request</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gL1QUbBH54_clf3Fs8CZZg.png" /></figure><p>“/users” is our endpoint so we can get the response if we goto “http://localhost/users” using postman and request type is get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjdLHQpw4bSDYEXPpb2rgg.png" /></figure><h3>Get Request With Parameter</h3><p>We can pass parameters like this. We need to put our parameter’s type the rute path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_RZzGaivYE0-j5Afb6ykw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TW61uYbDK_EhNnfZUsklbw.png" /></figure><h3>POST Request</h3><p>In post requests, we need to import request from flask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-as7XAvCl4KtDw-pDhdiJQ.png" /></figure><p>Then we can access the request body. And if we need to return data as JSON then we need to convert data as JSON. We can do the convert using “<em>jsonify</em>”. First, we need to import that too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZSU5KVQ-0fFcAKaDAD0Mw.png" /></figure><p>Now we can do post request and return data as JSON to client. Code looks like bellow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itpIoJQWn8J_APA6wt4yPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1K8N5uWwSnHkIAq32IS2w.png" /></figure><h3>PUT Request</h3><p>Put Request is more likely POST Request. Code is like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUNGQQX54IctT-yj4XQONQ.png" /></figure><h3>DELETE Request</h3><p>In Delete Request, we pass parameters and find the element by the parameter and delete that item. Code like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZmuH89AmzMNYikEIc4gpA.png" /></figure><p>Now I show you a full CRUD App using flask. In this example, my all data save in a variable but in the real world, we need to save data in a database.</p><p>In My Example, I will create users with name, age and job and display all users, display user by their name, if user not found display error messages, edit users by their name, and finally delete users by their name. Here is my Full Example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s0B6NxJJoSVEY0Zj36beDw.png" /></figure><p>Source code <a href="https://github.com/Hasi6/flask-rest-api"><em>here</em></a>.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e65e79a5e15" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/restful-api-with-python-and-flask-6e65e79a5e15">RESTful API with Python and Flask</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>