<?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 Chnarsimha on Medium]]></title>
        <description><![CDATA[Stories by Chnarsimha on Medium]]></description>
        <link>https://medium.com/@chnarsimha986?source=rss-664b4ff1b65b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JzRbWzUoNxUdrzBD</url>
            <title>Stories by Chnarsimha on Medium</title>
            <link>https://medium.com/@chnarsimha986?source=rss-664b4ff1b65b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:02:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chnarsimha986/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[Jenkins CI/CD Pipeline for Building and Pushing Docker Images of a Simple Hello World API…]]></title>
            <link>https://medium.com/@chnarsimha986/jenkins-ci-cd-pipeline-for-building-and-pushing-docker-images-of-a-simple-hello-world-api-49deee790110?source=rss-664b4ff1b65b------2</link>
            <guid isPermaLink="false">https://medium.com/p/49deee790110</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Chnarsimha]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 17:57:27 GMT</pubDate>
            <atom:updated>2024-02-08T17:57:27.575Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jenkins CI/CD Pipeline for Building and Pushing Docker Images of a Simple Hello World API Implemented in FastAPI to Docker Hub</h3><p>In this tutorial, we will guide you through the process of setting up a Jenkins CI/CD pipeline to automate the building and pushing of Docker images to Docker Hub. We will use a simple FastAPI “Hello World” application as our example code.</p><h3>About</h3><ul><li>Streamline your development workflow with Jenkins by creating a CI/CD pipeline that automates the build and push of Docker images.</li><li>This Jenkinsfile, integrated into your project, ensures seamless image generation from a Dockerfile and effortless deployment to Docker Hub.</li><li>Enjoy the benefits of versioned and tagged Docker images, as Jenkins dynamically assigns build numbers for easy tracking and management.</li><li>Elevate your containerized applications with a robust CI/CD pipeline, empowering you to focus on code changes while Jenkins handles the Docker image lifecycle.</li></ul><p><strong>Deploying FastAPI Application</strong>: deploying a FastAPI application effortlessly. Leveraging Docker and Jenkins CI/CD pipeline for a seamless and efficient deployment experience</p><h4>Requirements</h4><ul><li><strong>Jenkins Installed on EC2</strong>: Jenkins should be installed and running on your EC2 instance. You can access Jenkins through the web interface.</li></ul><h4><strong>Setup Ec2 instance</strong>:-</h4><p>Go to the AWS console and search for the EC2 instance <a href="https://aws.amazon.com/console">https://aws.amazon.com/console</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*61MTLCvi28sZWjWU_v4FTg.png" /><figcaption>For instance type iam taking t2micro</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*wliLeV-HDUq_ixCC9F5mbg.png" /><figcaption>Create a PEM file for the key pair named ‘key-pair-name.</figcaption></figure><p>Now click on the ‘Launch’ button, and it will show like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Hu15csVij-xnILxHMp67Q.png" /><figcaption>Ec2 lunched successfully with id</figcaption></figure><p>To download MobaXterm, please follow the link below <a href="https://mobaxterm.mobatek.net/download.html">https://mobaxterm.mobatek.net/download.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*IniwYKNUCVu0_PeGEfOjDg.png" /></figure><p>Now, click on the ‘Session’ option located at the top left. A window will pop up, where you can choose the SSH option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3k9FYfTjqhFJL-l4ZXX4Uw.png" /></figure><p>“In the ‘Remote Host’ field, enter your public IP address. In the ‘Specified User’ field, input ‘ubuntu’. Below that, under ‘Private Key,’ add the PEM file you saved on your local machine. click on ok</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Z7sCRUjzE8mZKDCA6OC4QQ.png" /><figcaption>ubuntu connection</figcaption></figure><p>install Jenkins requires Java to run, yet not all Linux distributions include Java by default. Additionally, <a href="https://www.jenkins.io/doc/book/platform-information/support-policy-java/">not all Java versions are compatible</a> with Jenkins.</p><pre>sudo apt update<br>sudo apt install fontconfig openjdk-17-jre<br>java -version</pre><p>Now, you need to execute the following commands to install Jenkins.</p><pre>sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \<br>  https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \<br>  https://pkg.jenkins.io/debian-stable binary/ | sudo tee \<br>  /etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br>sudo apt-get update<br>sudo apt-get install jenkins</pre><p>To start the jenkins you need to perfrom this command</p><pre> sudo systemctl enable jenkins<br> sudo systemctl start jenkins<br> sudo systemctl status jenkins</pre><p>In the AWS console, edit the inbound rules for the security group and add the rules as depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PywCK2xoEYFS7BqWj-Wzg.png" /><figcaption>The port should be set to run on 8080</figcaption></figure><p>After setting up the server, you can access your application by entering the IP address followed by the port number,like this:http://your_ip_address:8080 you will find this window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*t6UUdXYio2wLeTyS7F4Ugg.png" /><figcaption>copy var/lib/jenkins/secrets/initialAdaminpassword</figcaption></figure><p>in consloe you past this like as show below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhb2zhPg-4eEZ4nA5Ilm-Q.png" /><figcaption>You’ll find an ID that you can paste as the administrator password</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*To0GNzhoUFrFyiFSUjwC2Q.png" /><figcaption>click on install suggested plugins it will take some time</figcaption></figure><p>after will redirect this page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhFJB-XApWU_sRihlpKLEg.png" /><figcaption>Create your admin user with your details.</figcaption></figure><p>Now, to successfully access the Jenkins homepage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7YVSuxvGNv4w4Klq5kEHQ.png" /><figcaption>Jenkins Dashboard</figcaption></figure><ul><li>Docker Installed on Jenkins Server:Ensure that Docker is installed on the Jenkins server. You can use the official Docker installation instructions for your Linux distribution.</li></ul><pre>sudo apt update<br><br>sudo apt install -y apt-transport-https ca-certificates curl software-properties-common<br><br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg<br><br><br>echo &quot;deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br><br><br>sudo apt update<br><br>sudo apt install -y docker-ce docker-ce-cli containerd.io </pre><ul><li>Docker Hub Account:Create an account on Docker Hub if you don’t have one. Visit the Docker Hub Website: Open your web browser and go to the Docker Hub website: <a href="https://hub.docker.com/">https://hub.docker.com/</a> Click on “Sign Up”: Locate the “Sign Up” button on the top right corner of the page and click on it. Fill in Registration Details:Enter a valid email address.Choose a username for your Docker Hub account.Create a strong password. Create repo with test</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8idJxuN8H98Kd0qai2BoQ.png" /></figure><ul><li>Dockerfile in Your GitHub Repository:Your GitHub repository should contain a Dockerfile in the root directory. This Dockerfile defines the instructions for building your Docker image.</li><li>This is my repository; you can check it <a href="https://github.com/Narsi12/fastapijenkTOimage">https://github.com/Narsi12/fastapijenkTOimage</a></li><li>Here, I am building a Docker image for FastAPI this my Dockerfile</li></ul><pre># Use the official Python image as the base image<br>FROM python:3.9-slim<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the requirements file into the container<br>COPY requirements.txt .<br><br># Install dependencies<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy the FastAPI application code into the container<br>COPY app.py .<br><br># Expose the port that FastAPI will run on<br>EXPOSE 8080<br><br># Command to run the application using uvicorn<br>CMD [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8080&quot;]</pre><ul><li><strong>Jenkins Pipeline Configuration</strong>:Configure a Jenkins pipeline with the provided Jenkinsfile. Adjust the placeholders in the Jenkinsfile, such as repository URL, Docker Hub credentials, etc.</li></ul><pre>node {<br>    def app<br><br>    stage(&#39;Clone repository&#39;) {<br><br>        checkout scm<br>    }<br><br>    stage(&#39;Build image&#39;) {<br>  <br>       app = docker.build(&quot;narsimha2580/test&quot;)<br>    }<br><br>    stage(&#39;Test image&#39;) {<br><br>        app.inside {<br>            sh &#39;echo &quot;Tests passed&quot;&#39;<br>        }<br>    }<br><br>    stage(&#39;Push image&#39;) {<br>        <br>        docker.withRegistry(&#39;https://registry.hub.docker.com&#39;, &#39;docker-hub-credentials&#39;) {<br>            app.push(&quot;${env.BUILD_NUMBER}&quot;)<br>        }<br>    }<br>    <br>    stage(&#39;Trigger ManifestUpdate&#39;) {<br>                echo &quot;triggering updatemanifestjob&quot;<br>                build job: &#39;updatemanifest&#39;, parameters: [string(name: &#39;DOCKERTAG&#39;, value: env.BUILD_NUMBER)]<br>        }<br>}</pre><ul><li><strong>Webhook or Polling Setup</strong>: Set up a webhook in your GitHub repository to trigger the Jenkins pipeline on code changes. Alternatively, you can configure Jenkins to poll your repository for changes.</li><li><strong>Payload URL</strong>: publicIP with port and in trigger in webhook select pull request, pushes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FttnzWL-Uy1qK05mB7qKNA.png" /></figure><ul><li><strong>Docker Hub Credentials in Jenkins</strong>:In Jenkins, set up Docker Hub credentials. Go to “Jenkins” &gt; “Manage Jenkins” &gt; “Manage Credentials” &gt; “(select your domain)” &gt; “(select your credentials)”.</li><li>Now, you’ve added Docker Hub credentials to Jenkins. with username and password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAnX9DcIjexMlZpcVvrDmQ.png" /><figcaption>In credential add docker hub credential</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFgAfVUBnKHTbAPnbPJaJg.png" /></figure><ul><li><strong>Jenkins Plugins</strong>:Ensure that the necessary Jenkins plugins are installed. You may need plugins related to Docker integration and pipeline execution. Install them via the Jenkins web interface under “Manage Jenkins” &gt; “Manage Plugins.”</li><li>I already installed all plugins you check here</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHHe6YFOA0DXO3OH6SAxCA.png" /></figure><p>In Manage Jenkins you can add JDK installations and Git installations , Docker installations<br>for better understanding follow this youtube link :<br><a href="https://youtu.be/BePJ1bBWk3E?si=EE608NLIFRFldxYh">https://youtu.be/BePJ1bBWk3E?si=EE608NLIFRFldxYh</a><br>watch upto 5 mins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*YwGzBSexXIWL8N_IpJPcXQ.png" /></figure><ul><li><strong>Internet Access from Jenkins Server</strong>:Ensure that the Jenkins server has internet access to pull Docker images and push to Docker Hub.</li><li><strong>GitHub Integration</strong>:Jenkins should be able to access your GitHub repository. If it&#39;s a private repository, make sure to set up the necessary credentials or SSH keys.</li><li><strong>EC2 Security Group Configuration</strong>:Ensure that the security group associated with your EC2 instance allows traffic on the necessary ports for Jenkins and Docker.</li></ul><h4>Jenkins Dashboard:</h4><ul><li>in Dashboard page Now, click on the ‘New Item’ option located at the top left</li><li>Click on ‘Give Item Name,’ select ‘Pipeline,’ and click ‘OK</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*yGarj8hs-PML-bKGIYh7Kw.png" /></figure><ul><li>In the description, add your description, and in Build Triggers, select ‘GitHub hook trigger for GITScm polling</li><li>In the pipeline section, choose ‘Pipeline script from SCM,’ and under SCM, add the Git Repository URL. Specify your Branch Specifier as blank for ‘any. apply it and save</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRnAWH0WySyPn5trVFZvLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*x7g8JstW1iIiLU2rfxAPKQ.png" /></figure><p>Build will be triggered automatically as shown in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqap3T-ptSmzRioVkT01MQ.png" /></figure><ul><li>You can observe that all stages have been successfully completed in the image above. Now, navigate to the Docker Hub page, where you will find the image. If you wish to run the image, follow these commands<br>But u need to observe one thing that I also implemented the Trigger ManifesrUpdate for this you need to create a another jenkins and deployment.yml file<br>repolink : <a href="https://github.com/Narsi12/k8sfastapi">https://github.com/Narsi12/k8sfastapi</a></li></ul><p>It’s a manifest file and I given name as a <a href="https://github.com/Narsi12/k8sfastapi">k8sfastapi</a><br>jenkinsfile</p><pre>node {<br>    def app<br><br>    stage(&#39;Clone repository&#39;) {<br><br>        checkout scm<br>    }<br><br>    stage(&#39;Update GIT&#39;) {<br>            script {<br>                catchError(buildResult: &#39;SUCCESS&#39;, stageResult: &#39;FAILURE&#39;) {<br>                    withCredentials([usernamePassword(credentialsId: &#39;github&#39;, passwordVariable: &#39;GIT_PASSWORD&#39;, usernameVariable: &#39;GIT_USERNAME&#39;)]) {<br>                        //def encodedPassword = URLEncoder.encode(&quot;$GIT_PASSWORD&quot;,&#39;UTF-8&#39;)<br>                        sh &quot;git config user.email chnarsimha2580@gmail.com&quot;<br>                        sh &quot;git config user.name Narsi12&quot;<br>                        //sh &quot;git switch master&quot;<br>                        sh &quot;cat deployment.yaml&quot;<br>                        sh &quot;sed -i &#39;s+narsimha2580/test.*+narsimha2580/test:${DOCKERTAG}+g&#39; deployment.yaml&quot;<br>                        sh &quot;cat deployment.yaml&quot;<br>                        sh &quot;git add .&quot;<br>                        sh &quot;git commit -m &#39;Done by Jenkins Job changemanifest: ${env.BUILD_NUMBER}&#39;&quot;<br>                        sh &quot;git push @github.com/${GIT_USERNAME}/k8sfastapi.git&quot;&gt;https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/${GIT_USERNAME}/k8sfastapi.git HEAD:main&quot;<br>      }<br>    }<br>  }<br>}<br>}</pre><p>deployment.yaml</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  creationTimestamp: null<br>  labels:<br>    app: fastapidemo<br>  name: fastapidemo<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: fastapidemo<br>  strategy: {}<br>  template:<br>    metadata:<br>      creationTimestamp: null<br>      labels:<br>        app: fastapidemo<br>    spec:<br>      containers:<br>      - image: narsimha2580/test:10<br>        name: fastapidemo<br>        resources: {}<br>status: {}<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: lb-service<br>  labels:<br>    app: lb-service<br>spec:<br>  type: LoadBalancer<br>  ports:<br>  - port: 80<br>    targetPort: 8080<br>  selector:<br>    app: fastapidemo</pre><p>Create a new Jenkins item named “UpdateManifest”. When the “BuildImage” Jenkins pipeline is triggered, it should also trigger the “UpdateManifest” item to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVNPuyqWD6ibtLFYKjWB7w.png" /></figure><ul><li>You can observe that all stages have been successfully completed in the image above. Now, navigate to the Docker Hub page, where you will find the image. If you wish to run the image, follow these commands</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkET3ieXRnL_7TfSCzvpRw.png" /></figure><pre>docker run -p &lt;host-port&gt;:&lt;container-port&gt; -d &lt;your-dockerhub-username&gt;/&lt;your-image-name&gt;:&lt;tag&gt;<br><br>docker run -p 8081:8080 -d yourusername/yourimage:latest </pre><p>successfully set up a Jenkins CI/CD Pipeline for our projects. This means we can now automatically build and push our software as Docker images to Docker Hub. It’s like having a smart assistant that takes care of the heavy lifting in the development process, making things faster and more reliable. Exciting times ahead for smoother and more efficient development!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*GBYICdKgXrcqK1lD70UTjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*JWKS1iwjyV_Ju1yDJPr6pQ.png" /></figure><p>Now that our Continuous Integration (CI) process is complete, we are ready to commence Continuous Deployment (CD) using ArgoCD.</p><p><strong>Argocd Installation:</strong></p><p>Please follow the official documentation provided at this link for installing ArgoCD: <a href="https://argo-cd.readthedocs.io/en/stable/getting_started/">https://argo-cd.readthedocs.io/en/stable/getting_started/</a></p><p><strong>Kubectl Installtion</strong> :</p><p>. Please refer to the following link for instructions on installing Minikube and other Kubernetes tools: <a href="https://kubernetes.io/docs/tasks/tools/">https://kubernetes.io/docs/tasks/tools/</a>. Additionally, please install Minikube for future purposes.</p><p>Now we need to access the argocd by using the following command <strong>command </strong>: kubectl port-forward svc/argocd-server -n argocd 8000:443</p><pre>kubectl port-forward svc/argocd-server -n argocd 8000:443</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaPL0ww1qSBgI7nZSsIkrg.png" /></figure><p>click on “Continue to localhost(unsafe)”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu6rq9v9fqvmtuQqh6PwvA.png" /></figure><p>for getting the password follow the</p><pre>kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=&quot;{.data.password}&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbmG6TpfUCeBc7HVfBTjGA.png" /><figcaption>argocd password</figcaption></figure><p>Please encode the code and paste it as a Base64 string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*PX1uhY_bFBKYrj257fVzwQ.png" /></figure><p>Mention the username as <strong>admin </strong>and password is<strong> &lt;decode code&gt;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HISSiTqs1xV40LCFnALGig.png" /></figure><p>Create a +NEW APP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eLwZrGuTazDixHn69kZuA.png" /></figure><p>Please provide the URL of the k8sfastapi repository and include it below as demonstrated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4ySe60_K5lX25mApzMCLw.png" /></figure><p>When selecting the destination, please choose the cluster URL and namespace as illustrated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGrLZC60j9ZUULRXNSohvA.png" /></figure><p>Then click on Create</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*M0t99vgojeeNpV4INr9Xvg.png" /></figure><p>Upon clicking the application, you will be able to view the pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*me0ZS87XhV_1igNFNhBtRQ.png" /></figure><p>The pods are generate successfully !</p><p>now click on any pod and take that pod name follow the below command to access that pod</p><pre>kubectl port-forward pod/&lt;pod name&gt; 8083:8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*a5wlHuC4z98eA65FVywoFQ.png" /></figure><p>You will be able to access the content on your localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*GvjFOMDGB48b-dexDUZPvg.png" /></figure><p>Changes made to the `app.py` file will trigger the webhook, leading to the deletion of old pods and the generation of new pods. This entire process will be automated through Continuous Integration (CI) and Continuous Deployment (CD).</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Thank you for reading. I will continue to update this blog in the future and implement the most efficient methods for CI/CD pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49deee790110" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI App Deployment Using AWS Lambda And API Gateway]]></title>
            <link>https://blog.devgenius.io/fastapi-app-deployment-using-aws-lambda-and-api-gateway-31cb6611cb2d?source=rss-664b4ff1b65b------2</link>
            <guid isPermaLink="false">https://medium.com/p/31cb6611cb2d</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chnarsimha]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 07:55:44 GMT</pubDate>
            <atom:updated>2024-01-15T17:58:53.620Z</atom:updated>
            <content:encoded><![CDATA[<p>FastAPI is a modern, high-performance web framework for building APIs with Python. It is known for its speed, simplicity, and auto-generated interactive API documentation, leveraging Python type hints for robustness and efficiency in development. FastAPI <a href="https://github.com/tiangolo/fastapi"><em>https://github.com/tiangolo/fastapi</em></a><em> (repo link) </em>offers features like dependency injection, asynchronous capabilities, and seamless integration with OpenAPI and JSON Schema.</p><h4><strong><em>FastAPI in Containers -Docker :</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WdcE3mf9W8PrQlY57Vc0g.png" /><figcaption>Architecture diagram</figcaption></figure><p>One prevalent method for deploying FastAPI applications involves creating a Linux container image, typically accomplished through Docker. This image can then be deployed within Lambda. Employing Linux containers offers numerous advantages, such as enhanced security, reproducibility, ease of use, among other benefits.</p><p><strong>Preparatory Steps:</strong></p><p>Before commencing the deployment of a FastAPI docker container app, it’s essential to install specific software on your local machine for building the app’s container image and pushing it to ECR.</p><p>Please ensure the following tools are installed on your local system before initiating the deployment of the FastAPI container app:</p><ol><li>Python installation is required.<br>2. Docker needs to be installed.<br>3. Configure and install the AWS CLI.<br>4. Create an ECR Repository within your AWS Account.</li></ol><p><strong>STEPS:</strong></p><p>- Construct the FastAPI container image on the local machine.<br>- Push the container image to the ECR repository.<br>- Establish a lambda function utilizing the ECR image.<br>- Perform tests on the lambda function.<br>- Generate an API Gateway.<br>- Connect the API Gateway with the Lambda Function.<br>- Test the FastAPI application.<br>- Generate a Lambda URL and evaluate the FastAPI app.</p><p><strong>Construct the FastAPI container image on the local machine:</strong></p><p>I’ve implemented a basic FastAPI application that showcases plain text output.<br>Here is the structure of our repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*5-q3UUh6XkotykTkya_1Cg.png" /><figcaption>repo structure</figcaption></figure><p>app.py</p><pre>from fastapi import FastAPI<br>import mangum<br>import uvicorn<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def read_root():<br>    return {&quot;Hello&quot;: &quot;World&quot;}<br><br>handler = mangum.Mangum(app)<br><br>if __name__ == &quot;__main__&quot;:<br>   uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8080)</pre><p>Dockerfile:</p><pre>FROM public.ecr.aws/lambda/python:3.8<br>COPY . ${LAMBDA_TASK_ROOT}<br>WORKDIR /app<br>ARG DEBIAN_FRONTEND=noninteractive<br> <br>RUN yum update -y<br>RUN yum update -y python3 curl libcom_err ncurses expat libblkid libuuid libmount<br>RUN yum install ffmpeg libsm6 libxext6 python3-pip git -y<br> <br>RUN pip3 install fastapi --target &quot;${LAMBDA_TASK_ROOT}&quot;<br>RUN pip3 install mangum --target &quot;${LAMBDA_TASK_ROOT}&quot;<br> <br>COPY ./requirements.txt ./requirements.txt<br>RUN pip install -r ./requirements.txt<br>CMD [&quot;app.handler&quot;]</pre><p><strong>requirements.txt :</strong></p><pre>fastapi==0.68.0<br>uvicorn==0.15.0<br>mangum==0.10</pre><p><strong>What is Mangum:</strong></p><p>`Mangum` is an ASGI adapter for AWS Lambda that allows you to deploy ASGI applications, such as FastAPI, on AWS Lambda and API Gateway. It essentially acts as a bridge between FastAPI (which uses ASGI — Asynchronous Server Gateway Interface) and the serverless environment provided by AWS Lambda, enabling the deployment of FastAPI applications in the serverless architecture of AWS Lambda and API Gateway.</p><p><strong>Configuring AWS CLI:<br></strong>To connect to AWS using the access and secret keys, you can utilize the AWS Command Line Interface (CLI) and configure it with the provided access and secret keys for authentication.<br><strong>reference </strong>(<a href="https://youtu.be/N7MgJYlJd7M?si=Rjv7n6lIxn7w4xdZ">https://youtu.be/N7MgJYlJd7M?si=Rjv7n6lIxn7w4xdZ</a>)</p><p><strong>Create and upload the container image to the ECR repository.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eum3-IrafhChn-mEMzSEAQ.png" /><figcaption>Docker Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*KfVuOJgRblquTNVd26FspA.png" /><figcaption>Image pushed to ecr</figcaption></figure><h3>Create a lambda function using ECR image:</h3><p>Generate a Lambda function employing the ECR container image. Navigate to the Lambda resource console, click “Create Function,” select the container image option, and browse the image stored in the ECR repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KX22nQnweBw7vcbjm37JUA.png" /><figcaption>Lambda Function</figcaption></figure><p>You need to choose the container image for the previously mentioned Lambda function.<br>like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q32Yw93LaBSABV46TECzOQ.png" /><figcaption>Selecting the container image</figcaption></figure><p>After creating the function, proceed by performing the following steps:</p><ul><li>Select the “Test” option.<br>- Provide an Event Name.<br>- Choose the “apigateway-aws-proxy” template.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAHOyqPjNk_oPHFCnCrsQw.png" /><figcaption>Test in lambda</figcaption></figure><p><strong>Now modify the apigateway-aws-proxy json format as shown below:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*XLl3CSodNYn6YWgOCMGbtA.png" /><figcaption>Modifying the apigateway-aws-proxy</figcaption></figure><p>The endpoint for my resource and path is set as a forward slash (/), and the API method used is GET.</p><ul><li>&gt;Additionally, modify the configurations at the end of the apigateway-aws-proxy JSON format as depicted in the accompanying image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*O77T_w8HGsA1zw7pU30DHA.png" /><figcaption>Modifications on end of proxy</figcaption></figure><p><strong>Now click on the Test:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvtBP8kuiFfRvjuQuhM5bA.png" /><figcaption>Test is succeeded</figcaption></figure><p><strong>Generate an API Gateway : </strong>— REST API by navigating to the API Gateway console and selecting “Create API,” followed by choosing the option for building a REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*L6WMZ6F9TRzOvht-cXcTAQ.png" /><figcaption>Create API Gateway with REST API</figcaption></figure><p>Establish integration between the API Gateway and Lambda Function by performing the following actions:</p><ul><li>Generate a Resource for the API.<br>- Create a Method for the Resource.</li><li>if endpoint is ‘/’ then create method(enable lambda proxy integration)&gt;&gt; mention lambda function ARN</li><li>and if endpoint contains prefixes then first create resource and then create method(enable lambda proxy integration)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*kaLAkrQi6tin_NrBLjhURg.png" /><figcaption>Create Method Function In API Geateway</figcaption></figure><p>Note : Enable the lambda proxy integration option and also select the Your lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbaacObknQYAMlu7Yn8BEQ.png" /><figcaption>GET Menthod</figcaption></figure><p>Once the method is created, proceed to select the “Test” option as depicted in the image above and conduct testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kj7kLmOTm8anRs1kBwkSg.png" /><figcaption>Test Response successfully 200 status</figcaption></figure><ul><li>Once Resources and Method are created for API, then click on actions and select Deploy API and provide the required details like below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*GuCx2E5CIUPSX02de374wA.png" /><figcaption>deploy the api</figcaption></figure><h3>Test the FastAPI app :</h3><ul><li>Take the URL of the Deployment of API Gateway and hit it in the browser and you will get the JSON response from FastAPI app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsgEtBBOIZ_sBUWcupG-_Q.png" /><figcaption>getting the URL from deployed Api</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*EDBB_v0Rx4_K_wRMyqDbxA.png" /><figcaption>Final API Output</figcaption></figure><h3>Conclusion :</h3><p>You’re now ready to start creating your own highly performant APIs for your projects. If you want to dive deeper into the world of FastAPI, then you can follow the official <a href="https://fastapi.tiangolo.com/tutorial/"><em>User Guide</em></a> in the FastAPI documentation.</p><p>— — — — — — — — — — — — — — — -Thank You For Reading — — — — — — — — — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31cb6611cb2d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/fastapi-app-deployment-using-aws-lambda-and-api-gateway-31cb6611cb2d">FastAPI App Deployment Using AWS Lambda And API Gateway</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database migration from MongoDB to Amazon DynamoDB with Boto3]]></title>
            <link>https://medium.com/@chnarsimha986/effortless-data-transition-mongodb-to-dynamodb-migration-with-boto3-d2867d74597e?source=rss-664b4ff1b65b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2867d74597e</guid>
            <dc:creator><![CDATA[Chnarsimha]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 18:42:00 GMT</pubDate>
            <atom:updated>2023-07-10T06:07:13.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*h6KymTPzHgPS99iuZkRVPA.png" /></figure><p><strong>DynamoDB:</strong></p><p>⦁ DynamoDB is a fully managed NoSQL database service provided by Amazon Web Services (AWS). It offers fast and flexible storage for applications requiring low-latency access to data at any scale. DynamoDB is designed to provide high performance and automatic scalability, making it suitable for a wide range of use cases, from small-scale applications to large-scale enterprise systems.</p><p><strong>MongoDB:</strong></p><p>⦁ MongoDB is a widely used open-source NoSQL database system that provides high performance, flexibility, and scalability for storing and managing structured and unstructured data. It differs from traditional relational databases by offering a document-oriented data model, which allows for easy representation of complex hierarchical relationships and dynamic schemas.</p><p><strong>Data-Migration:</strong></p><p>⦁ Data migration refers to the process of transferring data from one system, storage, or format to another. It involves extracting data from a source, transforming it if necessary, and loading it into a target system or format. Data migration is typically performed when there is a need to switch to a new database, upgrade existing systems, consolidate data from multiple sources, or adopt new technologies.</p><p><strong>Boto3:</strong></p><p>⦁ Boto3 is the official AWS Software Development Kit (SDK) for Python, provided by Amazon Web Services. It allows developers to interact with various AWS services and resources programmatically using Python code. Boto3 simplifies the process of integrating Python applications with AWS services by providing an easy-to-use and comprehensive set of APIs.</p><p><strong>Creating a Table in DynamoDB using Boto3: Step-by-Step Guide:</strong></p><p>Here is how to connect Boto3 to the AWS services by entering your access key and secret key.<br>create a file in python with the name <br><strong>config.py</strong></p><pre>aws_access_key_id = &quot;&lt;your access key&gt;&quot;<br>aws_secret_access_key = &quot;&lt;your secret key&gt;&quot;<br>region = &quot;&lt;region name&gt;&quot;</pre><p>⦁ First, we must use boto3 to create a table in dynamodb.</p><p>⦁ To create a table in Dynamodb, adhere to the code below.</p><pre>import boto3<br>import botocore<br>from config import aws_access_key_id,aws_secret_access_key<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;,aws_access_key_id=aws_access_key_id,<br>                             aws_secret_access_key=aws_secret_access_key)<br><br>try:<br>    table = dynamodb.create_table(<br>        TableName=&#39;delivery&#39;,<br>        KeySchema=[<br>            {<br>                &#39;AttributeName&#39;: &#39;ID&#39;,<br>                &#39;KeyType&#39;: &#39;HASH&#39;<br>            }<br>        ],<br>        AttributeDefinitions=[<br>            {<br>                &#39;AttributeName&#39;: &#39;ID&#39;,<br>                &#39;AttributeType&#39;: &#39;S&#39;<br>            }<br>        ],<br>        ProvisionedThroughput={<br>            &#39;ReadCapacityUnits&#39;: 5,<br>            &#39;WriteCapacityUnits&#39;: 5<br>        }<br>    )<br>    print(&quot;Table created successfully!&quot;)<br><br>except botocore.exceptions.ClientError as e:<br>    if e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;ResourceInUseException&#39;:<br>        print(&quot;Table already exists.&quot;)<br>    else:<br>        print(&quot;An error occurred:&quot;, e)</pre><p>When creating a table in DynamoDB, the fields KeySchema, AttributeDefinitions, and ProvisionedThroughput must all be filled out.<br>Here you can find detailed information about Dynamodb Boto3.</p><p>(<a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html</a>)</p><p>In aws</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*-YKRFxy5OcLWILQaZGbB3g.png" /></figure><p><strong>lets create a function in boto3 to migrate data from mongodb to dynamodb:</strong></p><p>⦁to connect with mongodb install</p><pre>pip install pymongo</pre><p>We are using the mongoclient to establish a connection to the MongoDB database, and following is a process for migrating data from MongoDB to Dynamodb.</p><pre>import pymongo<br>import boto3<br><br>myclient = pymongo.MongoClient(&quot;mongodb://localhost:27017/&quot;)<br>mydb = myclient[&quot;&lt;your database name&gt;&quot;]<br>mycol = mydb[&#39;&lt;your collection name&gt;&#39;]<br>data = mycol.find() # To retrieve all records from your collection we are using (find) method.<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)#boto3 connect with dynamodb service<br><br>table = dynamodb.Table(&#39;&lt;your dynamodb table name&gt;&#39;)<br><br>def convert_float_values_to_strings(data):<br>    if isinstance(data, float): #dynamodb is not accepting the float values.<br>        return str(data)<br>    elif isinstance(data, list):<br>        return [convert_float_values_to_strings(item) for item in data]<br>    elif isinstance(data, dict):<br>        return {key: convert_float_values_to_strings(value) for key, value in data.items()}<br>    else:<br>        return data<br><br>for item in data:<br>    item = convert_float_values_to_strings(item)<br><br>    dynamodb_item = {<br>        &#39;ID&#39;: str(item[&#39;_id&#39;]),  # these are the feild names which are present in your collection<br>        &#39;userID&#39;: item[&#39;userID&#39;],<br>        &#39;order_type&#39;: item[&#39;order_type&#39;],<br>        &#39;qty&#39;: item[&#39;qty&#39;],<br>        &#39;temp_order_id&#39;: item[&#39;temp_order_id&#39;],<br>        &#39;date_info&#39;: item[&#39;date_info&#39;].isoformat(),  <br>        &#39;destination_info&#39;: item[&#39;destination_info&#39;],<br>        &#39;order_id&#39;: item[&#39;order_id&#39;],<br>        &#39;source_info&#39;: item[&#39;source_info&#39;],<br>        &#39;status&#39;: item[&#39;status&#39;],<br>    }<br><br>    table.put_item(Item=dynamodb_item) #The put_item method is used to insert records into a DynamoDB table.<br><br>print(&quot;Data migration to DynamoDB completed.&quot;)<br><br>  </pre><p>Using Boto3, we establish a connection to the DynamoDB service. Additionally, we utilize the MongoClient to retrieve data from our MongoDB collection. To reference our DynamoDB table, we use the line table = dynamodb.Table(&#39;delivery_tab33&#39;). It&#39;s important to note that DynamoDB does not accept float values directly, so we convert them to string format as explained in this resource (<a href="https://stackoverflow.com/questions/50764201/python-migration-mongodb-to-dynamodb-float-error">https://stackoverflow.com/questions/50764201/python-migration-mongodb-to-dynamodb-float-error</a>). Next, we iterate through our data and specify the fields present in our collection. Finally, by employing table.put_item(Item=dynamodb_item), we insert the records into DynamoDB.</p><p>In aws :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Ouem-Q8lblnhFy10tzniog.png" /></figure><p>Form view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*n_lqC-xS4R7H8a0Ny7s7EQ.png" /></figure><p>Json view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*boZW6gqVqps37NB_WFIm9A.png" /><figcaption>Json type</figcaption></figure><p>And that’s it.<br>I appreciate you taking the time to read my blog. Thank you for your interest and support. If you have any questions or feedback, please don’t hesitate to reach out. Once again, thank you for your time and for engaging with my blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6D65XGTz7Ljd6VD0mj5ATw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2867d74597e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Authentication System Using FastApi and PostgreSql Login,Logout]]></title>
            <link>https://medium.com/@chnarsimha986/fastapi-login-logout-changepassword-4c12e92d41e2?source=rss-664b4ff1b65b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c12e92d41e2</guid>
            <category><![CDATA[login]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Chnarsimha]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 13:23:54 GMT</pubDate>
            <atom:updated>2023-06-27T07:33:31.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, some extremely good men out there have come up with brand new framework for Python to mitigate the issues mentioned above, called FastAPI<br><a href="https://github.com/tiangolo/fastapi"><em>https://github.com/tiangolo/fastapi</em></a><em> (repo link)<br></em>In this tutorial, we are going to explore FastAPI, more specifically building RESTful APIs and deploying the application on server.</p><p>FastAPI is a Web framework for developing RESTful APIs in Python. It fully supports asynchronous programming and can run with Uvicorn and Gunicorn. Uvicorn is a lightning-fast ASGI server implementation.</p><p>In this tutorial we are buliding the FastApi-boiler-plate-code, which includes user-registration,user-login with JWT token authentication.</p><h3>Create a database engine:</h3><p>We must first build a database engine for models. <br><strong><em>database.py</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*vgiv_vCiwI03NbnIsAcvRw.png" /></figure><p>here we created a<strong> database engine</strong></p><p><strong>Create Models:</strong></p><p>Now we are creating models for user.<br><strong><em>models.py</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*uM87sYEW5AubC_sUylqCqg.png" /><figcaption>user models</figcaption></figure><p><strong>Create Basemodel for models using pydentic:</strong></p><p>Pydantic is a simple Python library with beautiful and era defining feature, data validation at runtime. Although Python is dynamically typed language, it does not mean that we really need our data to be of any data type and without Pydantic, it is very difficult and time consuming task to validate data at runtime in Python. Using this key feature of Pydantic, FastAPI gives some very easy and useful features which frameworks like ExpressJs, of dynamically typed language like Python and JavaScript, lack. Let’s see those key features of FastAPI which are based upon Pydantic and make developer’s life a lot easier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*rhq_pK9BxeYFBQV1BJRuXA.png" /><figcaption>pydentic</figcaption></figure><p>create <strong><em>schemas.py file</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*MMMqmd2xT-QkH_inXz3Nxg.png" /></figure><p><strong>User Registration :</strong></p><p>The first step in this process is to establish a user registration API. Postgresql is the database we’ll use, and the user registration fields are username, email, and password and the password will save in database as encrypted format.</p><p>create <strong><em>main.py file</em></strong></p><pre>import schemas<br>import models<br>from models import User<br>from database import Base, engine, SessionLocal<br>from fastapi import FastAPI, Depends, HTTPException,status<br>from sqlalchemy.orm import Session<br><br>Base.metadata.create_all(engine)<br>def get_session():<br>    session = SessionLocal()<br>    try:<br>        yield session<br>    finally:<br>        session.close()<br>app=FastAPI()<br><br>@app.post(&quot;/register&quot;)<br>def register_user(user: schemas.UserCreate, session: Session = Depends(get_session)):<br>    existing_user = session.query(models.User).filter_by(email=user.email).first()<br>    if existing_user:<br>        raise HTTPException(status_code=400, detail=&quot;Email already registered&quot;)<br><br>    encrypted_password =get_hashed_password(user.password)<br><br>    new_user = models.User(username=user.username, email=user.email, password=encrypted_password )<br><br>    session.add(new_user)<br>    session.commit()<br>    session.refresh(new_user)<br><br>    return {&quot;message&quot;:&quot;user created successfully&quot;}</pre><p>Now user registration is completed .</p><p>Note:Please execute some basic operations on Fastapi if you are a beginner; only then will you be able to follow this lesson.</p><p><strong>User Login Functionality:<br></strong>What is JSON Web Token?</p><p>JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the <strong>HMAC</strong> algorithm) or a public/private key pair using <strong>RSA</strong> or <strong>ECDSA</strong>.</p><p>Although JWTs can be encrypted to also provide secrecy between parties, we will focus on <em>signed</em> tokens. Signed tokens can verify the <em>integrity</em> of the claims contained within it, while encrypted tokens <em>hide</em> those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.<br>To generate the access token and refresh token before moving on to the <strong>main.p</strong>y file, you must first construct the<strong><em> utils.py file</em></strong>.</p><pre>import os<br>from passlib.context import CryptContext<br>from datetime import datetime, timedelta<br>from typing import Union, Any<br>from jose import jwt<br><br>ACCESS_TOKEN_EXPIRE_MINUTES = 30  # 30 minutes<br>REFRESH_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days<br>ALGORITHM = &quot;HS256&quot;<br>JWT_SECRET_KEY = &quot;narscbjim@$@&amp;^@&amp;%^&amp;RFghgjvbdsha&quot;   # should be kept secret<br>JWT_REFRESH_SECRET_KEY = &quot;13ugfdfgh@#$%^@&amp;jkl45678902&quot;<br><br>password_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)<br><br>def get_hashed_password(password: str) -&gt; str:<br>    return password_context.hash(password)<br><br><br>def verify_password(password: str, hashed_pass: str) -&gt; bool:<br>    return password_context.verify(password, hashed_pass)<br><br>def create_access_token(subject: Union[str, Any], expires_delta: int = None) -&gt; str:<br>    if expires_delta is not None:<br>        expires_delta = datetime.utcnow() + expires_delta<br>        <br>    else:<br>        expires_delta = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)<br>         <br>    <br>    to_encode = {&quot;exp&quot;: expires_delta, &quot;sub&quot;: str(subject)}<br>    encoded_jwt = jwt.encode(to_encode, JWT_SECRET_KEY, ALGORITHM)<br>     <br>    return encoded_jwt<br><br>def create_refresh_token(subject: Union[str, Any], expires_delta: int = None) -&gt; str:<br>    if expires_delta is not None:<br>        expires_delta = datetime.utcnow() + expires_delta<br>    else:<br>        expires_delta = datetime.utcnow() + timedelta(minutes=REFRESH_TOKEN_EXPIRE_MINUTES)<br>    <br>    to_encode = {&quot;exp&quot;: expires_delta, &quot;sub&quot;: str(subject)}<br>    encoded_jwt = jwt.encode(to_encode, JWT_REFRESH_SECRET_KEY, ALGORITHM)<br>    return encoded_jwt</pre><p>We must build a second tokentable model in order to store the token in our database. Why? Why because the logout function token should be added to a blacklist, but how? We can only blacklist those tokens in the logout function when we store them in a single table.<br><strong><em>models.py</em></strong> file add below code</p><pre>from sqlalchemy import Column, Integer, String, DateTime,Boolean<br>from database import Base<br>import datetime<br>class User(Base):<br>    __tablename__ = &#39;users&#39;<br>    id = Column(Integer, primary_key=True)<br>    username = Column(String(50),  nullable=False)<br>    email = Column(String(100), unique=True, nullable=False)<br>    password = Column(String(100), nullable=False)<br><br>class TokenTable(Base):<br>    __tablename__ = &quot;token&quot;<br>    user_id = Column(Integer)<br>    access_toke = Column(String(450), primary_key=True)<br>    refresh_toke = Column(String(450),nullable=False)<br>    status = Column(Boolean)<br>    created_date = Column(DateTime, default=datetime.datetime.now)</pre><p>now in<strong><em> schemas.py</em></strong> file add below code this is comple schemas.py file i will explain what is it in further tutorial</p><pre>from pydantic import BaseModel<br>import datetime<br>class UserCreate(BaseModel):<br>    username: str<br>    email: str<br>    password: str<br><br>class requestdetails(BaseModel):<br>    email:str<br>    password:str<br>        <br>class TokenSchema(BaseModel):<br>    access_token: str<br>    refresh_token: str<br><br>class changepassword(BaseModel):<br>    email:str<br>    old_password:str<br>    new_password:str<br><br>class TokenCreate(BaseModel):<br>    user_id:str<br>    access_token:str<br>    refresh_token:str<br>    status:bool<br>    created_date:datetime.datetime</pre><p>in<strong><em> main.py file</em></strong></p><pre>import schemas<br>import models<br>import jwt<br>from datetime import datetime <br>from models import User,TokenTable<br>from database import Base, engine, SessionLocal<br>from sqlalchemy.orm import Session<br>from fastapi import FastAPI, Depends, HTTPException,status<br>from fastapi.security import OAuth2PasswordBearer<br>from auth_bearer import JWTBearer<br>from functools import wraps<br>from utils import create_access_token,create_refresh_token,verify_password,get_hashed_password<br>ACCESS_TOKEN_EXPIRE_MINUTES = 30  # 30 minutes<br>REFRESH_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days<br>ALGORITHM = &quot;HS256&quot;<br>JWT_SECRET_KEY = &quot;narscbjim@$@&amp;^@&amp;%^&amp;RFghgjvbdsha&quot;   # should be kept secret<br>JWT_REFRESH_SECRET_KEY = &quot;13ugfdfgh@#$%^@&amp;jkl45678902&quot;<br><br>@app.post(&#39;/login&#39; ,response_model=schemas.TokenSchema)<br>def login(request: schemas.requestdetails, db: Session = Depends(get_session)):<br>    user = db.query(User).filter(User.email == request.email).first()<br>    if user is None:<br>        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=&quot;Incorrect email&quot;)<br>    hashed_pass = user.password<br>    if not verify_password(request.password, hashed_pass):<br>        raise HTTPException(<br>            status_code=status.HTTP_400_BAD_REQUEST,<br>            detail=&quot;Incorrect password&quot;<br>        )<br>    <br>    access=create_access_token(user.id)<br>    refresh = create_refresh_token(user.id)<br><br>    token_db = models.TokenTable(user_id=user.id,  access_toke=access,  refresh_toke=refresh, status=True)<br>    db.add(token_db)<br>    db.commit()<br>    db.refresh(token_db)<br>    return {<br>        &quot;access_token&quot;: access,<br>        &quot;refresh_token&quot;: refresh,<br>    }</pre><p>in login function we are requesting the two feilds they are email and password. And it is already mentioned in schemas.py file with class name as <strong>requestdetails</strong></p><p>We must now access those tokens in our get and post methods, am I correct?<br>Tokens must be mentioned in our functions before being used in headers; to do this, a new file called <strong><em>auth_bearer.py</em></strong> must be created.<br>add the following code in your <strong>auth_bearer.py</strong> file</p><pre>import jwt<br>from jwt.exceptions import InvalidTokenError<br>from fastapi import FastAPI, Depends, HTTPException,status<br>from fastapi import Request, HTTPException<br>from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials<br>from models import TokenTable<br><br>ACCESS_TOKEN_EXPIRE_MINUTES = 30  # 30 minutes<br>REFRESH_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days<br>ALGORITHM = &quot;HS256&quot;<br>JWT_SECRET_KEY = &quot;narscbjim@$@&amp;^@&amp;%^&amp;RFghgjvbdsha&quot;   # should be kept secret<br>JWT_REFRESH_SECRET_KEY = &quot;13ugfdfgh@#$%^@&amp;jkl45678902&quot;<br><br>def decodeJWT(jwtoken: str):<br>    try:<br>        # Decode and verify the token<br>        payload = jwt.decode(jwtoken, JWT_SECRET_KEY, ALGORITHM)<br>        return payload<br>    except InvalidTokenError:<br>        return None<br><br><br>class JWTBearer(HTTPBearer):<br>    def __init__(self, auto_error: bool = True):<br>        super(JWTBearer, self).__init__(auto_error=auto_error)<br><br>    async def __call__(self, request: Request):<br>        credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)<br>        if credentials:<br>            if not credentials.scheme == &quot;Bearer&quot;:<br>                raise HTTPException(status_code=403, detail=&quot;Invalid authentication scheme.&quot;)<br>            if not self.verify_jwt(credentials.credentials):<br>                raise HTTPException(status_code=403, detail=&quot;Invalid token or expired token.&quot;)<br>            return credentials.credentials<br>        else:<br>            raise HTTPException(status_code=403, detail=&quot;Invalid authorization code.&quot;)<br><br>    def verify_jwt(self, jwtoken: str) -&gt; bool:<br>        isTokenValid: bool = False<br><br>        try:<br>            payload = decodeJWT(jwtoken)<br>        except:<br>            payload = None<br>        if payload:<br>            isTokenValid = True<br>        return isTokenValid<br><br>jwt_bearer = JWTBearer()</pre><p>applying jwt token in our get and post api calls you can check this jwtbearer</p><p>(<a href="https://testdriven.io/blog/fastapi-jwt-auth/">https://testdriven.io/blog/fastapi-jwt-auth/</a>) <br> continue in <strong><em>main.py</em></strong> file</p><pre>from auth_bearer import JWTBearer<br><br>@app.get(&#39;/getusers&#39;)<br>def getusers( dependencies=Depends(JWTBearer()),session: Session = Depends(get_session)):<br>    user = session.query(models.User).all()<br>    return user</pre><p>now we are going to jump into <strong>changepassword API :</strong></p><pre>@app.post(&#39;/change-password&#39;)<br>def change_password(request: schemas.changepassword, db: Session = Depends(get_session)):<br>    user = db.query(models.User).filter(models.User.email == request.email).first()<br>    if user is None:<br>        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=&quot;User not found&quot;)<br>    <br>    if not verify_password(request.old_password, user.password):<br>        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=&quot;Invalid old password&quot;)<br>    <br>    encrypted_password = get_hashed_password(request.new_password)<br>    user.password = encrypted_password<br>    db.commit()<br>    <br>    return {&quot;message&quot;: &quot;Password changed successfully&quot;}</pre><p>As our tutorial comes to a close, simply click the logout API.</p><p>Let’s start with a logout endpoint to allow the user to leave our application without the fear of anyone else in the same device using its token.</p><p>This endpoint is going to set the token as invalid. In order to do this, we are going to add the token to a list of blacklisted tokens.</p><p>This change make us also validate, for each request, if the token is not in the list of blacklisted tokens.</p><p>but the same user token will stay in database even if we logout so to slove this issue we need to delete the saved token from database but how?</p><p>here is the solution : We are storing the token in the login API right there, and we are directly applying one status in models as True so that token will store in the database with the status as True now in the logout function, we are making status as false. util now everything is fine, so up until this point, tokens are not deleting from the database while being generated in the utils.py file, where we are applying the time right, so let’s calculate some math here now created-date in token-table subtracts time limit in refresh token.</p><pre>@app.post(&#39;/logout&#39;)<br>def logout(dependencies=Depends(JWTBearer()), db: Session = Depends(get_session)):<br>    token=dependencies<br>    payload = jwt.decode(token, JWT_SECRET_KEY, ALGORITHM)<br>    user_id = payload[&#39;sub&#39;]<br>    token_record = db.query(models.TokenTable).all()<br>    info=[]<br>    for record in token_record :<br>        print(&quot;record&quot;,record)<br>        if (datetime.utcnow() - record.created_date).days &gt;1:<br>            info.append(record.user_id)<br>    if info:<br>        existing_token = db.query(models.TokenTable).where(TokenTable.user_id.in_(info)).delete()<br>        db.commit()<br>        <br>    existing_token = db.query(models.TokenTable).filter(models.TokenTable.user_id == user_id, models.TokenTable.access_toke==token).first()<br>    if existing_token:<br>        existing_token.status=False<br>        db.add(existing_token)<br>        db.commit()<br>        db.refresh(existing_token)<br>    return {&quot;message&quot;:&quot;Logout Successfully&quot;} </pre><p>Okay, so if you use this token in get or post calls, we need to receive a message stating that your token has been blacklisted. To solve this problem, we need to create a decorator and apply a condition such as: if the given token is present in the headers and its status is True, we will return the data; if its status is False, we will return a message stating that your token has been blacklisted.</p><pre>def token_required(func):<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>    <br>        payload = jwt.decode(kwargs[&#39;dependencies&#39;], JWT_SECRET_KEY, ALGORITHM)<br>        user_id = payload[&#39;sub&#39;]<br>        data= kwargs[&#39;session&#39;].query(models.TokenTable).filter_by(user_id=user_id,access_toke=kwargs[&#39;dependencies&#39;],status=True).first()<br>        if data:<br>            return func(kwargs[&#39;dependencies&#39;],kwargs[&#39;session&#39;])<br>        <br>        else:<br>            return {&#39;msg&#39;: &quot;Token blocked&quot;}<br>        <br>    return wrapper</pre><p>hey guys,</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c12e92d41e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>