<?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 Lalitvavdara on Medium]]></title>
        <description><![CDATA[Stories by Lalitvavdara on Medium]]></description>
        <link>https://medium.com/@lalitvavdara2016?source=rss-a607c3676387------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GG02DZ8S7O4NCPd-XKYVDw.png</url>
            <title>Stories by Lalitvavdara on Medium</title>
            <link>https://medium.com/@lalitvavdara2016?source=rss-a607c3676387------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:02:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lalitvavdara2016/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[The Grug-Brained Developer’s Guide to 10x AI Productivity]]></title>
            <link>https://lalitvavdara2016.medium.com/the-grug-brained-developers-guide-to-10x-ai-productivity-14ceed69b291?source=rss-a607c3676387------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ceed69b291</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Lalitvavdara]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 10:18:55 GMT</pubDate>
            <atom:updated>2026-05-04T05:51:34.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vS5KYfnuFGj0POc56pg-A.png" /></figure><blockquote>How understanding transformers, respecting complexity, and following a disciplined workflow turns AI from a fancy autocomplete into an actual force multiplier.</blockquote><p>There is a specific kind of developer who gets almost nothing from AI coding tools. They type a vague prompt, get mediocre output, paste it in, watch it explode, and go: <em>“yeah, AI isn’t there yet.”</em> They are half right.</p><p>AI is not there yet (<em>for them</em>) because they haven’t changed how they think.</p><p>Then there’s a second kind of developer who has quietly become 10x more output-capable in the last two years. Not smarter. Not better at picking tools. They just understood three things simultaneously: how large language models <em>actually</em> work under the hood, why complexity is still the apex predator even when a machine writes the code, and how to run a disciplined workflow that keeps the AI on a leash rather than letting it hallucinate its way across the codebase.</p><p>This article connects all three. Grab coffee. It’s a long one.</p><h3>Part I: What the Machine Actually Is</h3><h3>Stop calling it “understanding”</h3><p>Before you can use an AI coding assistant well, you need to disabuse yourself of a comfortable fiction: that the model “understands” your code the way a senior engineer does. It doesn’t. It <em>predicts</em>.</p><p>The Transformer architecture, born at Google in 2017 for translation, is still the foundation of every model you’re using today. Claude Opus 4.6, GPT-5.4, Gemini 3.1 Pro — all descendants of the same core idea. Every word in GPT still matters:</p><ul><li><strong>Generative</strong>: it produces new sequences from learned patterns, not a database lookup</li><li><strong>Pretrained</strong>: it learned from enormous text corpora before you ever typed a prompt</li><li><strong>Transformer</strong>: attention-based architecture that lets every token attend to every other token in context</li></ul><blockquote>The model has no persistent memory between calls, no understanding of intent in any human sense, and hard limits on how much context it can hold. It is a sophisticated next-token predictor operating over a fixed window.</blockquote><h3>The actual pipeline, no PhD required</h3><p>Here’s what actually happens when you ask Claude to “refactor this function”:</p><p><strong>1. Tokenization:</strong> Your text breaks into tokens, roughly 3–4 characters each. “refactor” maps to [&quot;ref&quot;, &quot;act&quot;, &quot;or&quot;]. Modern models have vocabularies of 50k-100k+ chunks.</p><p><strong>2. Embedding:</strong> Each token maps to a high-dimensional vector. Similar concepts cluster nearby. “bug” and “error” overlap significantly. “function” and “method” are neighbors.</p><p><strong>3. Attention:</strong> Tokens attend to each other and update their representations based on context. This is how “model” means something different in “ML model” vs “fashion model.”</p><p><strong>4. Feed-forward + repeat:</strong> Dense network layers refine each token’s representation. Then attention again. This alternation repeats dozens of times through the network.</p><p><strong>5. Prediction + sample:</strong> The final vector projects into logits across the entire vocabulary. Softmax converts to probabilities. One token is sampled. Repeat until done.</p><h3>The 2026 model landscape</h3><p>The core architecture above is universal. What separates the current top coding models is context window, benchmark performance, and what they’re actually good at:</p><p>ModelContext Window SWE-bench VerifiedBest for <strong>Claude Opus 4.6 </strong>200K (1M beta) 80.8% Long-context codebase work, agentic coding <strong>GPT-5.4</strong>272K standardCompetitiveMultimodal, enterprise, intelligent routing <strong>Gemini 3.1 Pro</strong>1M tokensCompetitiveMassive codebase analysis, abstract reasoning <strong>DeepSeek V4 </strong>128K High Budget-conscious, top Python on Chatbot Arena</p><p>SWE-bench Verified is the benchmark that actually matters for developers: it measures a model’s ability to resolve real GitHub issues end-to-end, autonomously. Claude Opus 4.6 leads here at 80.8%.</p><p>The bigger story: top models are now within 1–2 points of each other on most benchmarks. There is no universal winner. Smart developers in 2026 route across 2–3 models depending on the task rather than picking one and staying loyal.</p><h3>So why does this change how you prompt?</h3><p><strong>Context is computation.</strong> The model attends to what’s in its window. Everything outside doesn’t exist. Giving Claude the right files and constraints upfront isn’t courtesy; it’s load-bearing information.</p><p><strong>Ambiguity compounds.</strong> Because each token is predicted from prior tokens, vagueness early in your prompt cascades. A fuzzy task description produces a plausible-sounding but wrong architecture, which produces a plausible-sounding but wrong implementation, which produces code that <em>looks</em> like it works and doesn’t.</p><p><strong>Recency bias is real.</strong> Content near the end of a long prompt gets more attention weight than stuff buried in the middle. Put your hard constraints first <em>and</em> last. If the model keeps ignoring a rule, put it alone at the top.</p><p><strong>Hallucination is a token prediction artifact, not a bug.</strong> The model always produces an answer because softmax always produces a distribution. There is no built-in “I don’t know.” You have to build skepticism into your review process.</p><h3>Part II: The Eternal Enemy Has Not Changed</h3><blockquote>“Complexity is a spirit demon that enters the codebase through well-meaning but ultimately very clubbable developers.” ~ The Grug Brained Developer</blockquote><p>AI does not solve the complexity problem. AI <em>turbocharges</em> it.</p><p>The developer who once took three days to build a fragile over-engineered abstraction can now build it in three hours. The instinct to reach for generics, to factor prematurely, to introduce a microservice where a function would do, AI makes all of that faster and more prolific. <strong>The complexity demon now has a motor.</strong></p><h3>The AI-specific complexity traps</h3><p><strong>The Abstraction Trap</strong> Ask for a payment handler, get an abstract PaymentProcessor base class, a factory, three implementations, and a registry, even if you just need to call Stripe. Enterprise patterns are overrepresented in training data. You have to fight this explicitly.</p><p><strong>The Completeness Trap</strong> AI wants to give you a <em>complete</em> answer. Ask for one function, get the function, its tests, docs, error handling, usage examples, and alternative approaches. Most of it is waste you’ll maintain forever. If you ask to create 1 pay_bill function, only 1 pay_bill function should be created, nothing additional.</p><p><strong>The DRY Trap</strong> AI follows Don’t Repeat Yourself aggressively. Sometimes a tiny bit of duplication is clearer than an abstraction that barely saves three lines. Repeat code is sometimes better than a complex DRY solution. Know when to let it repeat.</p><p><strong>The Microservice Trap</strong> AI will design you a distributed system at the drop of a hat. A network boundary is a concurrency problem + a latency problem + an operational problem. Unless you have demonstrated need, default to a monolith with clear internal boundaries.</p><h3>The right mental model: AI as a senior contractor</h3><p>Think of the AI as a very fast, very knowledgeable contractor who has worked on many codebases (but has never worked on <em>yours</em>), doesn’t know your constraints, and defaults to whatever seemed popular in training data.</p><p>A good contractor relationship means:</p><ul><li>You do the architecture. The contractor implements.</li><li>You define the interfaces. The contractor fills them in.</li><li>You review everything before it merges. The contractor does <strong>not</strong> have merge rights.</li></ul><h3>Say no, often and loudly</h3><p>The best weapon against complexity has always been the magic word: <strong>no.</strong></p><p>“No, we don’t need a base class for this.” “No, this doesn’t need its own service.” “No, don’t add documentation to code that explains itself.”</p><p>The 80/20 rule applies harder than ever. Most features can be delivered at 80% spec with 20% of the complexity. AI can help you find that path, but only if you ask: <em>“What is the simplest implementation that would work here?”</em> is one of the most productive prompts you can write.</p><h3>Part III: The Workflow That Actually Scales</h3><h3>Stop going directly to implementation</h3><p>The typical AI usage pattern:</p><blockquote><em>Think of feature -&gt; open Claude -&gt; describe it vaguely -&gt; paste output -&gt; debug for 3 hours -&gt; repeat -&gt; it kind of works -&gt; ship it -&gt; regret it at 3am.</em></blockquote><p>This is the equivalent of describing requirements verbally to a junior developer and asking them to start coding immediately. It produces the output you deserve.</p><p>The workflow that actually scales has five phases. None can be safely skipped.</p><h3>Phase 1: Deep Research</h3><p>Before writing a single line of spec, the AI must understand the existing system. Make it read and report before it suggests anything.</p><pre>Read this folder in depth and understand how it works,<br>what it does, and all its specificities.<br><br>When done, write a detailed report of your learnings<br>in research.md. Do not suggest any implementation yet.</pre><p>The output is a research.md file: a structured document that forces the model to externalize its understanding before pattern-matching toward solutions. This catches wrong assumptions when they&#39;re cheap to fix (text), not expensive to fix (merged code).</p><p>For bug hunting specifically, add one critical instruction:</p><pre>Go through the flow deeply and look for potential bugs.<br>Keep researching until you find all issues.<br>Do not stop early.</pre><p>“Do not stop early” is doing real work. Without it, the model finds the first plausible issue, proposes a fix, and feels done. Most bugs are not the first plausible thing.</p><h3>Phase 2: Implementation Planning</h3><p>Only after research exists do you plan. The critical constraint is one sentence:</p><blockquote><strong><em>Do not implement anything yet. Only write the plan.</em></strong></blockquote><p>This creates a deliberate gate. It forces both you and the model to think through architecture, file paths, interfaces, and edge cases before a single line of production code is written.</p><p>The plan should contain:</p><ul><li>File paths for each change</li><li>Architecture decisions and their rationale</li><li>Key interface snippets (not implementations)</li><li>A numbered todo list with phases</li></ul><p>This is also where Chesterton’s Fence applies: before the plan removes or replaces existing code, it must demonstrate understanding of <em>why that code exists</em>. Surface that question in planning, it’s cheap there. In production it costs you your weekend.</p><h3>Phase 3: Annotation Cycles</h3><p>The plan is a draft. You review it, add notes inline, pass it back:</p><pre>I added notes to the document. Address all the notes<br>and update the document accordingly.<br><br>Do not implement yet.</pre><p>This cycle may run two or three times for complex features. Every iteration is far cheaper than discovering the same problem in code review.</p><p>If scope needs cutting:</p><pre>Remove &lt;feature&gt; from the plan. Not implementing this now.</pre><p>If an approach needs overriding:</p><pre>Use &lt;library/approach&gt; instead.<br>The signatures of these functions must not change.<br>Adapt the implementation instead.</pre><h3>Phase 4: Implementation (finally)</h3><pre>Implement it all.<br><br>Mark each task complete as you finish it.<br>Do not stop until all phases are done.<br>Do not add unnecessary comments or JSDoc.<br>Do not use any or unknown types.<br><br>Continuously run typecheck and fix issues as you go.</pre><p>The typecheck instruction is important: it uses the tool’s own feedback loop to catch errors locally. The comment instruction is anti-complexity philosophy applied directly. Well-written code documents itself. If you need a comment to explain what a line does, the line should be rewritten, not commented.</p><p>When implementation goes wrong, the corrections are short and surgical:</p><pre># Missed something<br>You didn&#39;t implement &lt;function&gt;. Add it.<br><br># Wrong location<br>This should be in &lt;module&gt;. Move it.<br># Nuclear option<br>I reverted the changes.<br>Now only implement: &lt;narrow scope&gt;.<br>Nothing else.</pre><p>That last one (revert and narrow scope) is the right call more often than you’d think. When the model has gone off-rails and correction cost exceeds value, the cheapest path is rewinding to a clean state.</p><h3>Phase 5: Context Management and Rewinding</h3><p>Claude Code lets you press Escape twice to see all messages and jump back to an earlier point. This isn’t just undo; it’s <em>context management.</em></p><p>When a debugging detour has polluted the conversation with 15 messages about a red herring, rewinding removes that noise. Combined with the # shortcut to record persistent memory, this is how you prevent the model from making the same mistake across sessions.</p><p><strong>The memory trick:</strong> When the model makes a repeatable mistake, rewind past the error, use # to add a memory about the correct approach, continue. It won&#39;t make that mistake again in this project, across all future sessions.</p><h3>Part IV: The Tooling Layer</h3><h3>Build your environment deliberately</h3><p>AI output quality is highly dependent on feedback loop tightness. The faster the model can see whether code is correct, the less iteration you need.</p><p>Tools;</p><p><strong>LSP Servers: </strong>Gives Claude real-time type info, symbol resolution, error feedback. The model checks its output against your actual type system.</p><p><strong>Superpowers: </strong>Skills framework that enforces TDD cycles, four-phase systematic debugging, and Socratic brainstorming before coding. Slash commands like /brainstorming and /execute-plan bake the research-plan-implement workflow directly into Claude Code.</p><p><strong>ccstatus: </strong>Shows token usage and remaining context window. Prevents the conversation that grew so long the model forgot the beginning.</p><p><strong>Context7: </strong>Pulls live library documentation into context. The model can&#39;t hallucinate API signatures it can look up.</p><p><strong>Playwright: </strong>Browser integration tests: high enough to verify real behavior, low enough to be debuggable.Medium</p><p><strong>Caveman plugin: </strong>Forces terse prompts. Less tokens in, less noise, more focused output. Terseness forces precision.</p><h3>Testing philosophy in an AI-assisted world</h3><p>When AI writes your unit tests, it writes them against the implementation it just wrote. This creates a hall of mirrors: tests pass because they encode the same assumptions as the implementation, not because the system is correct.</p><p>The practical model:</p><ul><li><strong>Unit tests</strong> at the start, to get moving, not to be precious about</li><li><strong>Integration tests</strong> as cut points emerge and stabilize (this is the sweet spot)</li><li><strong>A small, sacred end-to-end suite</strong> on critical user journeys, zero tolerance for intermittency</li><li><strong>Regression tests always</strong>: reproduce the bug with a test <em>before</em> fixing it</li></ul><h3>Part V: The Grug Principles, Applied to AI</h3><p>Here is the distillation: hard-won wisdom mapped directly to AI-assisted development.</p><p><strong>Complexity is still the enemy.</strong> AI accelerates code production. It does not reduce the cognitive load of maintaining complex code. Every abstraction the AI adds, you will maintain. The standard has not changed; the throughput of code that violates it has increased dramatically.</p><p><strong>Say no to AI suggestions.</strong> When the model proposes an abstraction you didn’t ask for, or introduces a dependency to solve a problem a function could solve, say no. This is not being ungrateful. It is being the senior engineer on the project.</p><p><strong>Understand before changing.</strong> AI does not know your code’s history. It doesn’t know why a particular check exists, or why a seeming inefficiency is actually load-bearing. You must apply that judgment. Always. Chesterton’s Fence is not optional.</p><p><strong>Log aggressively.</strong> AI-generated code often omits logging. Add it back at every major branch, every external call, every state transition. In production, your logs are your debugger.</p><p><strong>Fear of Looking Dumb (FOLD) kills teams.</strong> If you cannot explain what the AI-generated code does, you should not merge it. Senior developers saying “this is too complex for me to understand” is not weakness. It is the most important signal on a team.</p><h3>A day in the life</h3><p>PhaseTimeWhat happensContext setup15 minNew session, fresh context, relevant files only, constraints upfrontResearch30–60 minClaude reads and reports, you verify understandingPlanning20–40 minPlan generated, annotated, iterated, approvedImplementationVariableExecute plan, review each step, typecheck continuouslyWrap-up15 minCommit, write memory note, carry constraints forward</p><p>The total overhead versus “just prompting” is maybe 30%. The reduction in debugging, rework, and technical debt payback is easily 50%+. The math works.</p><h3>Conclusion: Smol Brain, Big Output</h3><p>The developers getting 10x from AI are not the ones who found the magic prompt. They’re the ones who understood that the model is a <strong>sophisticated pattern matcher operating in a fixed context window</strong> (not an oracle), who kept complexity as their primary enemy rather than handing it to a machine to multiply, and who built a disciplined workflow that gates implementation behind research and planning.</p><p>The Grug Brained Developer was always right: <strong>complexity is the apex predator.</strong> AI has not changed that. If anything, it has raised the stakes. The developer who does not respect complexity can now create far more of it, far faster, than ever before.</p><p>But the developer who has internalized these principles, who understands the transformer architecture well enough to know what to put in context, who applies anti-complexity principles to every AI suggestion, and who runs the research -&gt; plan -&gt; implement cycle with discipline, that developer has a <strong>genuine force multiplier.</strong></p><p>The machine is fast. You have to be wise.</p><p><em>Sources: The Grug Brained Developer (grugbrain.dev) · Attention Is All You Need, Vaswani et al. (2017) · Crafting Interpreters, Robert Nystrom · Minimal Claude Code Setup workflow</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ceed69b291" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering with AI Tools in 2026: Why Understanding Matters More Than Ever]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://lalitvavdara2016.medium.com/engineering-with-ai-tools-in-2026-why-understanding-matters-more-than-ever-893a0b33c70f?source=rss-a607c3676387------2"><img src="https://cdn-images-1.medium.com/max/1024/1*bbsKiL3GPrBJADd_fyxK_A.png" width="1024"></a></p><p class="medium-feed-snippet">Sometime last year, I realized something slightly uncomfortable.</p><p class="medium-feed-link"><a href="https://lalitvavdara2016.medium.com/engineering-with-ai-tools-in-2026-why-understanding-matters-more-than-ever-893a0b33c70f?source=rss-a607c3676387------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://lalitvavdara2016.medium.com/engineering-with-ai-tools-in-2026-why-understanding-matters-more-than-ever-893a0b33c70f?source=rss-a607c3676387------2</link>
            <guid isPermaLink="false">https://medium.com/p/893a0b33c70f</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lalitvavdara]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 12:17:28 GMT</pubDate>
            <atom:updated>2026-01-04T12:17:28.437Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How I Decreased API Response Time by 89.30% in Python]]></title>
            <link>https://python.plainenglish.io/how-i-decreased-api-response-time-by-89-30-in-python-7057d20f6aef?source=rss-a607c3676387------2</link>
            <guid isPermaLink="false">https://medium.com/p/7057d20f6aef</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[back-end-development]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lalitvavdara]]></dc:creator>
            <pubDate>Thu, 13 May 2021 14:08:04 GMT</pubDate>
            <atom:updated>2021-05-21T10:51:32.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrMKiec3DjRg0OM7UcoraA.png" /><figcaption>Make your APIs faster</figcaption></figure><p>API response time is an important factor to look for if you want to build fast and scalable applications.</p><p>While working on a client’s project I had a task where I needed to integrate a third-party API for the project. This means that the Client’s project API response time will now also depend on this third-party API.</p><p>Everything works fine if we just need to make a single query to the API and return the results for that query, things start getting worse when we need to make multiple queries and return results for each query we made.</p><p>For demonstrating how to make multiple requests efficiently we will use this simple <a href="https://api.datamuse.com/words?rel_rhy=hello&amp;max=100">Rhyming word API</a>.</p><p>For example, suppose we want to find rhyming words for all the words present in [“hello”, “mellow”, “cat&quot;, &quot;rat&quot;, “dog”, “frog”, “mouse”, “sparrow”, “man”, “women”] one might think of implementing a code like this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528220%252C226%252C230%252C0%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D31px%26ph%3D30px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%252520requests%25252C%252520time%25250A%25250Awords%252520%25253D%252520%25255B%252522hello%252522%25252C%252520%252522mellow%252522%25252C%252520%252522cat%252522%25252C%252520%252522rat%252522%25252C%252520%252522dog%252522%25252C%252520%252522frog%252522%25252C%252520%252522mouse%252522%25252C%252520%252522sparrow%252522%25252C%252520%252522man%252522%25252C%252520%252522women%252522%25255D%25250A%25250Adef%252520make_req_syncronously%2528words_arr%2529%25253A%25250A%252520%252520%252520%252520final_res%252520%25253D%252520%25255B%25255D%25250A%252520%252520%252520%252520for%252520word%252520in%252520words_arr%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520url%252520%25253D%252520f%252522https%25253A%25252F%25252Fapi.datamuse.com%25252Fwords%25253Frel_rhy%25253D%25257Bword%25257D%252526max%25253D100%252522%25250A%252520%252520%252520%252520%252520%252520%252520%252520response%252520%25253D%252520requests.get%2528url%2529%25250A%252520%252520%252520%252520%252520%252520%252520%252520json_response%252520%25253D%252520response.json%2528%2529%25250A%252520%252520%252520%252520%252520%252520%252520%252520for%252520item%252520in%252520json_response%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520rhyming_word%252520%25253D%252520item.get%2528%252522word%252522%25252C%252520%252522%252522%2529%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520final_res.append%2528%25257B%252522word%252522%25253A%252520word%25252C%252520%252522rhyming_word%252522%25253A%252520rhyming_word%25257D%2529%25250A%252520%252520%252520%252520return%252520final_res%25250A%25250Awithout_async_start_time%252520%25253D%252520time.time%2528%2529%25250Aresponse%252520%25253D%252520make_req_syncronously%2528words%2529%25250Atime_without_async%252520%25253D%252520time.time%2528%2529%252520-%252520without_async_start_time%25250A%25250Aprint%2528%252522total%252520time%252520for%252520with%252520synchronous%252520execution%252520%25253E%25253E%252520%252522%25252C%252520time_without_async%25252C%252520%252522%252520seconds%252522%2529%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528220%25252C226%25252C230%25252C0%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D31px%26ph%3D30px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%25252520requests%2525252C%25252520time%2525250A%2525250Awords%25252520%2525253D%25252520%2525255B%25252522hello%25252522%2525252C%25252520%25252522mellow%25252522%2525252C%25252520%25252522cat%25252522%2525252C%25252520%25252522rat%25252522%2525252C%25252520%25252522dog%25252522%2525252C%25252520%25252522frog%25252522%2525252C%25252520%25252522mouse%25252522%2525252C%25252520%25252522sparrow%25252522%2525252C%25252520%25252522man%25252522%2525252C%25252520%25252522women%25252522%2525255D%2525250A%2525250Adef%25252520make_req_syncronously%252528words_arr%252529%2525253A%2525250A%25252520%25252520%25252520%25252520final_res%25252520%2525253D%25252520%2525255B%2525255D%2525250A%25252520%25252520%25252520%25252520for%25252520word%25252520in%25252520words_arr%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520url%25252520%2525253D%25252520f%25252522https%2525253A%2525252F%2525252Fapi.datamuse.com%2525252Fwords%2525253Frel_rhy%2525253D%2525257Bword%2525257D%25252526max%2525253D100%25252522%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520response%25252520%2525253D%25252520requests.get%252528url%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520json_response%25252520%2525253D%25252520response.json%252528%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520for%25252520item%25252520in%25252520json_response%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520rhyming_word%25252520%2525253D%25252520item.get%252528%25252522word%25252522%2525252C%25252520%25252522%25252522%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520final_res.append%252528%2525257B%25252522word%25252522%2525253A%25252520word%2525252C%25252520%25252522rhyming_word%25252522%2525253A%25252520rhyming_word%2525257D%252529%2525250A%25252520%25252520%25252520%25252520return%25252520final_res%2525250A%2525250Awithout_async_start_time%25252520%2525253D%25252520time.time%252528%252529%2525250Aresponse%25252520%2525253D%25252520make_req_syncronously%252528words%252529%2525250Atime_without_async%25252520%2525253D%25252520time.time%252528%252529%25252520-%25252520without_async_start_time%2525250A%2525250Aprint%252528%25252522total%25252520time%25252520for%25252520with%25252520synchronous%25252520execution%25252520%2525253E%2525253E%25252520%25252522%2525252C%25252520time_without_async%2525252C%25252520%25252522%25252520seconds%25252522%252529%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ff752229e32725fa50c8b624bfa5a9f/href">https://medium.com/media/4ff752229e32725fa50c8b624bfa5a9f/href</a></iframe><p>you will see that this approach takes approximately 9.479 seconds to search rhyming words for each word present in the Words list. Can you imagine you open a site and it takes 10 seconds to load? just because someone wrote this horrible code in the backend.</p><p>To better understand this look at this graph of how we make requests in this synchronous approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WckG0Guo1i-cfMfLSNHWBA.png" /><figcaption>Synchronous Requests vs. Time Graph</figcaption></figure><p>As you see we make 1st request for (“hello”) word then wait for it to return the result and then append it to the list we want to return, and the same for each word in the list. This is an extremely time-consuming way of implementing these.</p><h3>So, how can we improve this?</h3><p>Well, that’s where Async/wait comes to our help. Let’s understand how we can make multiple requests simultaneously with the following Python code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528220%252C226%252C230%252C0%2529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D31px%26ph%3D30px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%252520asyncio%25250Aimport%252520aiohttp%252520%252520%252523%252520external%252520library%25250Aimport%252520time%25250A%25250Awords%252520%25253D%252520%25255B%252522hello%252522%25252C%252520%252522mellow%252522%25252C%252520%252522cat%252522%25252C%252520%252522rat%252522%25252C%252520%252522dog%252522%25252C%252520%252522frog%252522%25252C%252520%252522mouse%252522%25252C%252520%252522sparrow%252522%25252C%252520%252522man%252522%25252C%252520%252522women%252522%25255D%25250A%25250Aasync%252520def%252520main%2528%2529%25253A%25250A%252520%252520%252520%252520headers%252520%25253D%252520%25257B%2527content-type%2527%25253A%252520%2527application%25252Fjson%2527%25257D%25250A%252520%252520%252520%252520async%252520with%252520aiohttp.ClientSession%2528headers%25253Dheaders%2529%252520as%252520session%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520tasks%252520%25253D%252520%25255B%25255D%252520%252520%252523%252520for%252520storing%252520all%252520the%252520tasks%252520we%252520will%252520create%252520in%252520the%252520next%252520step%25250A%252520%252520%252520%252520%252520%252520%252520%252520for%252520word%252520in%252520words%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520task%252520%25253D%252520asyncio.ensure_future%2528get_rhyming_words%2528session%25252C%252520word%2529%2529%252520%252520%252523%252520means%252520get%252520this%252520process%252520started%252520and%252520move%252520on%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520%252520tasks.append%2528task%2529%25250A%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252523%252520.gather%2528%2529%252520will%252520collect%252520the%252520result%252520from%252520every%252520single%252520task%252520from%252520tasks%252520list%25250A%252520%252520%252520%252520%252520%252520%252520%252520%252523%252520here%252520we%252520use%252520await%252520to%252520wait%252520till%252520all%252520the%252520requests%252520have%252520been%252520satisfied%25250A%252520%252520%252520%252520%252520%252520%252520%252520all_results%252520%25253D%252520await%252520asyncio.gather%2528%252Atasks%2529%25250A%252520%252520%252520%252520%252520%252520%252520%252520combined_list%252520%25253D%252520merge_lists%2528all_results%2529%25250A%252520%252520%252520%252520%252520%252520%252520%252520return%252520combined_list%25250A%25250A%25250Aasync%252520def%252520get_rhyming_words%2528session%25252C%252520word%2529%25253A%25250A%252520%252520%252520%252520url%252520%25253D%252520f%252522https%25253A%25252F%25252Fapi.datamuse.com%25252Fwords%25253Frel_rhy%25253D%25257Bword%25257D%252526max%25253D1000%252522%25250A%252520%252520%252520%252520async%252520with%252520session.get%2528url%2529%252520as%252520response%25253A%25250A%252520%252520%252520%252520%252520%252520%252520%252520result_data%252520%25253D%252520await%252520response.json%2528%2529%25250A%252520%252520%252520%252520%252520%252520%252520%252520return%252520result_data%25250A%25250A%25250Aasync_func_start_time%252520%25253D%252520time.time%2528%2529%25250Aresponse2%252520%25253D%252520asyncio.get_event_loop%2528%2529.run_until_complete%2528main%2528words%2529%2529%25250Atime_with_async%252520%25253D%252520time.time%2528%2529%252520-%252520async_func_start_time%25250A%25250Aprint%2528%252522%25255CnTotal%252520time%252520with%252520async%25252Fawait%252520execution%252520%25253E%25253E%252520%252522%25252C%252520time_with_async%25252C%252520%252522%252520seconds%252522%2529%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528220%25252C226%25252C230%25252C0%252529%26t%3Dnight-owl%26wt%3Dnone%26l%3Dpython%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D31px%26ph%3D30px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dimport%25252520asyncio%2525250Aimport%25252520aiohttp%25252520%25252520%25252523%25252520external%25252520library%2525250Aimport%25252520time%2525250A%2525250Awords%25252520%2525253D%25252520%2525255B%25252522hello%25252522%2525252C%25252520%25252522mellow%25252522%2525252C%25252520%25252522cat%25252522%2525252C%25252520%25252522rat%25252522%2525252C%25252520%25252522dog%25252522%2525252C%25252520%25252522frog%25252522%2525252C%25252520%25252522mouse%25252522%2525252C%25252520%25252522sparrow%25252522%2525252C%25252520%25252522man%25252522%2525252C%25252520%25252522women%25252522%2525255D%2525250A%2525250Aasync%25252520def%25252520main%252528%252529%2525253A%2525250A%25252520%25252520%25252520%25252520headers%25252520%2525253D%25252520%2525257B%252527content-type%252527%2525253A%25252520%252527application%2525252Fjson%252527%2525257D%2525250A%25252520%25252520%25252520%25252520async%25252520with%25252520aiohttp.ClientSession%252528headers%2525253Dheaders%252529%25252520as%25252520session%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520tasks%25252520%2525253D%25252520%2525255B%2525255D%25252520%25252520%25252523%25252520for%25252520storing%25252520all%25252520the%25252520tasks%25252520we%25252520will%25252520create%25252520in%25252520the%25252520next%25252520step%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520for%25252520word%25252520in%25252520words%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520task%25252520%2525253D%25252520asyncio.ensure_future%252528get_rhyming_words%252528session%2525252C%25252520word%252529%252529%25252520%25252520%25252523%25252520means%25252520get%25252520this%25252520process%25252520started%25252520and%25252520move%25252520on%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520tasks.append%252528task%252529%2525250A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252523%25252520.gather%252528%252529%25252520will%25252520collect%25252520the%25252520result%25252520from%25252520every%25252520single%25252520task%25252520from%25252520tasks%25252520list%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252523%25252520here%25252520we%25252520use%25252520await%25252520to%25252520wait%25252520till%25252520all%25252520the%25252520requests%25252520have%25252520been%25252520satisfied%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520all_results%25252520%2525253D%25252520await%25252520asyncio.gather%252528%25252Atasks%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520combined_list%25252520%2525253D%25252520merge_lists%252528all_results%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520return%25252520combined_list%2525250A%2525250A%2525250Aasync%25252520def%25252520get_rhyming_words%252528session%2525252C%25252520word%252529%2525253A%2525250A%25252520%25252520%25252520%25252520url%25252520%2525253D%25252520f%25252522https%2525253A%2525252F%2525252Fapi.datamuse.com%2525252Fwords%2525253Frel_rhy%2525253D%2525257Bword%2525257D%25252526max%2525253D1000%25252522%2525250A%25252520%25252520%25252520%25252520async%25252520with%25252520session.get%252528url%252529%25252520as%25252520response%2525253A%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520result_data%25252520%2525253D%25252520await%25252520response.json%252528%252529%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%25252520%25252520return%25252520result_data%2525250A%2525250A%2525250Aasync_func_start_time%25252520%2525253D%25252520time.time%252528%252529%2525250Aresponse2%25252520%2525253D%25252520asyncio.get_event_loop%252528%252529.run_until_complete%252528main%252528words%252529%252529%2525250Atime_with_async%25252520%2525253D%25252520time.time%252528%252529%25252520-%25252520async_func_start_time%2525250A%2525250Aprint%252528%25252522%2525255CnTotal%25252520time%25252520with%25252520async%2525252Fawait%25252520execution%25252520%2525253E%2525253E%25252520%25252522%2525252C%25252520time_with_async%2525252C%25252520%25252522%25252520seconds%25252522%252529%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea5942a932f6ebd75ad37c026b13ae67/href">https://medium.com/media/ea5942a932f6ebd75ad37c026b13ae67/href</a></iframe><p>here we create a Task for each request also called an Couritine in Python. In this implementation, we start a task but don’t wait for it to complete we simply move on and start a new task.</p><p>Finally, after we are done with creating all the tasks, we wait till we have result from each task, then we simply merge all the results from tasks using merge_lists function and return a combined list containing all the results.</p><p>The time it takes to search rhyming words for all the words in words list is approximate 1 second which is way better than what we had in the previous approach.</p><p>The requests vs time graph will now look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tho7yKVz8ay5MjKCEU44UQ.png" /><figcaption>Asynchronous Requests vs. Time Graph</figcaption></figure><p>As you can see in the graph by the time we initiate the final request we will have some of the previous requests already completed.</p><p>Here is the Python code for you to compare both implementations.</p><pre><em>import </em>requests, time</pre><pre>words = [&quot;hello&quot;, &quot;mellow&quot;, &quot;cat&quot;, &quot;rat&quot;, &quot;dog&quot;, &quot;frog&quot;, &quot;mouse&quot;, &quot;sparrow&quot;, &quot;man&quot;, &quot;women&quot;]</pre><pre><em>def </em>make_req_syncronously(words_arr):<br>    final_res = []<br>    <em>for </em>word <em>in </em>words_arr:<br>        url = f&quot;https://api.datamuse.com/words?rel_rhy={word}&amp;max=100&quot;<br>        response = requests.get(url)<br>        json_response = response.json()<br>        <em>for </em>item <em>in </em>json_response:<br>            rhyming_word = item.get(&quot;word&quot;, &quot;&quot;)<br>            final_res.append({&quot;word&quot;: word, &quot;rhyming_word&quot;: rhyming_word})<br>    <em>return </em>final_res</pre><pre>without_async_start_time = time.time()<br>response = make_req_syncronously(words)<br>time_without_async = time.time() - without_async_start_time<br><em>#<br>print</em>(&quot;total time for with synchronous execution &gt;&gt; &quot;, time_without_async, &quot; seconds&quot;)</pre><pre><em>import </em>asyncio<br><em>import </em>aiohttp  <em># external library</em><br></pre><pre><em>def </em>merge_lists(results_from_fc):<br>    <em>&quot;&quot;&quot;<br>    Function for merging multiple lists<br>    &quot;&quot;&quot;<br>    </em>combined_list = []<br>    <em>for </em>li <em>in </em>results_from_fc:<br>        combined_list.extend(li)</pre><pre>    <em>return </em>combined_list<br></pre><pre><em>async def </em>main():<br>    headers = {&#39;content-type&#39;: &#39;application/json&#39;}<br>    <em>async with </em>aiohttp.ClientSession(headers=headers) <em>as </em>session:<br>        tasks = []  <em># for storing all the tasks we will create in the next step<br>        for </em>word <em>in </em>words:<br>            task = asyncio.ensure_future(get_rhyming_words(session, word))  <em># means get this process started and move on<br>            </em>tasks.append(task)</pre><pre>        <em># .gather() will collect the result from every single task from tasks list<br>        # here we use await to wait till all the requests have been satisfied<br>        </em>all_results = <em>await </em>asyncio.gather(*tasks)<br>        combined_list = merge_lists(all_results)<br>        <em>return </em>combined_list<br></pre><pre><em>async def </em>get_rhyming_words(session, word):<br>    url = f&quot;https://api.datamuse.com/words?rel_rhy={word}&amp;max=1000&quot;<br>    <em>async with </em>session.get(url) <em>as </em>response:<br>        result_data = <em>await </em>response.json()<br>        <em>return </em>result_data<br></pre><pre>async_func_start_time = time.time()<br>response2 = asyncio.get_event_loop().run_until_complete(main())<br>time_with_async = time.time() - async_func_start_time</pre><pre><em>print</em>(&quot;\nTotal time with async/await execution &gt;&gt; &quot;, time_with_async, &quot; seconds&quot;)</pre><pre>total_improvement = (time_without_async - time_with_async) / time_without_async * 100<br><em>print</em>(f&quot;\n{&#39;*&#39; * 100}\n{&#39; &#39; * 32}Improved by {total_improvement} %\n{&#39;*&#39; * 100}&quot;)</pre><p>Thank you for taking the time to read <a href="https://www.lalitvavdara.me/">my</a> blog.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7057d20f6aef" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/how-i-decreased-api-response-time-by-89-30-in-python-7057d20f6aef">How I Decreased API Response Time by 89.30% in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating twillio SendGrid web API with Nextjs.]]></title>
            <link>https://lalitvavdara2016.medium.com/integrating-twillio-sendgrid-web-api-with-nextjs-3b2e5ce8d741?source=rss-a607c3676387------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b2e5ce8d741</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[sendgrid]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Lalitvavdara]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 18:30:17 GMT</pubDate>
            <atom:updated>2021-04-18T18:30:17.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tvj0KtojJ6mPzYMosEz0Fw.png" /></figure><p>Whenever developing any web app whether it be some static site or some dynamic site, in most of the cases we require some type of contact form, from which we can send or receive emails.</p><h3>What is Next.js?</h3><blockquote><em>It is used to build server-side rendering and static web applications using React.</em></blockquote><h3>What is SendGrid?</h3><blockquote><em>SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to whitelist services and real-time analytics. In short, </em><strong><em>it is used to send emails.</em></strong></blockquote><p>Assuming that you already have a next.js app setup let’s start with integrating SendGrid API to send emails, if you don’t have one check out this <a href="https://nextjs.org/docs/api-reference/create-next-app">guide</a>, on how to create the Next.js app.</p><p>There are two ways in which you can achieve this, one is by using the external <a href="https://www.npmjs.com/package/@sendgrid/mail">library</a> from SendGrid and the second is by making a POST request to https://api.sendgrid.com/v3/mail/send with all the required data, this is more suitable if you don&#39;t want to include any new library in your project for just sending emails.</p><p>Let’s see how can you send emails with SendGrid web API in Nextjs, create a file sendMail.js in the utils folder of your project&#39;s root directory. Now, your project&#39;s directory structure should look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*Go4IU9WNmBLGUU2HDzmOOw.png" /><figcaption>File Structure after creating sendMailToMe.js</figcaption></figure><p>add the following code to your sendMailToMe.js file</p><pre>import fetch from &quot;node-fetch&quot;;<br><br>const SENDGRID_API_URL = &quot;https://api.sendgrid.com/v3/mail/send&quot;;<br>const SENDGRID_API_KEY = process.env.NEW_SENDGRID_API_KEY;<br><br>const sendMailToMe = async (<br>   recepient_email, // email_address to send mail<br>  name_, // from name on email<br>  subject = &quot;sample subject&quot;,<br>  client_message, // value we receive from our contact form<br>  client_email // value we receive from our contact form<br>) =&gt; {<br>  const sgResponse = await fetch(SENDGRID_API_URL, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      Authorization: `Bearer ${SENDGRID_API_KEY}`,<br>    },<br>    body: JSON.stringify({<br>      personalizations: [<br>        {<br>          to: [<br>            {<br>              email: recepient_email,<br>            },<br>          ],<br>          subject: subject,<br>        },<br>      ],<br>      from: {<br>        email: &quot;YOUR VERIFIED SENDGRID MAIL HERE&quot;,<br>        name: &quot;YOUR NAME&quot;,<br>      },<br>      content: [<br>        {<br>          type: &quot;text/html&quot;,<br>          value: `&lt;strong&gt;Client Name: ${name_} &lt;/strong&gt; \n &lt;p&gt; <br>                  sent you a query regarding &lt;strong&gt;${subject}&lt;/strong&gt;&lt;/p&gt;<br>                  \n &lt;p&gt;Client&#39;s Message: &lt;strong&gt;${client_message}&lt;/strong&gt;&lt;\p&gt; <br>                  &lt;p&gt;Client&#39;s Email : &lt;strong&gt; ${client_email} &lt;/strong&gt;&lt;/p&gt;`,<br>        },<br>      ],<br>    }),<br>  });<br>  return sgResponse;<br>};<br><br>export { sendMailToMe };</pre><p>here we are using node-fetch for making a POST request so you need to install it through npm i node-fetch it is a lightweight module that brings window.fetch to Node.js, and also this function expects some values that we will include from our contact form. You will need SendGrid <a href="https://sendgrid.com/docs/ui/account-and-settings/api-keys/">API key</a> and store it in next.config.js as env variable to send emails and also verify a <a href="https://sendgrid.com/docs/ui/sending-email/sender-verification/">Sender Identity</a>.</p><p>Then, we need to create an API endpoint in Next.js that we will use to send data from our contact form, this is done by creating a new file in pages/api folder. This api folder is a special folder in Nextjs which is used to create all the api endpoints of your Nextjs app, and these endpoints are only invoked when they are required.</p><p>so add senMail.js to the pages/api folder of your app like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*9gehLV3BJxsIvPUmliYWBA.png" /><figcaption>File Structure after creating ssenMail.js</figcaption></figure><p>add the following code to your sendMail.js file</p><pre>import { sendMailQueryToMe } from &quot;../../utils/sendMailToMe&quot;;<br><br>export default async function handler(req, res) {<br>  if (req.method === &quot;POST&quot;) {<br>    // req.body carries all the data<br><br>    try {<br>      const { email, name_, subject, client_message } = req.body;<br><br>      if (<br>        typeof (email || name_ || subject || client_message) === &quot;undefined&quot;<br>      ) {<br>        console.log(&quot; ************* Invalid Data received ************ &quot;);<br><br>        return res<br>          .status(400)<br>          .send({ error: &quot;bad request, missing required data!&quot; });<br>      } else {<br>        //  Data received as expected<br>        try {<br>          const sendGridResponse = await sendMailQueryToMe(<br>            &quot;your_mail@gmail.com&quot;,<br>            name_,<br>            subject,<br>            client_message,<br>            email<br>          );<br><br>          return res.status(200).send({<br>            sg_response: sendGridResponse,<br>          });<br>        } catch (err) {<br>          console.log(<br>            &quot;ERROR WHILE SENDING MAIL TO *YOU* THROUGH WEB API &gt;&gt; &quot;,<br>            err<br>          );<br><br>          return res.status(400).send({<br>            err_message: &quot;bad request&quot;,<br>          });<br>        }<br>      }<br>    } catch (err) {<br>      console.log(&quot;Err while sending Mail through send grid &gt;&gt; &quot;, err);<br>      return res<br>        .status(400)<br>        .send({ error: &quot;Error in sendgrid Service.&quot;, errMsg: err });<br>    }<br>  }<br><br>  res.status(400).send({ error: &quot;bad request&quot; });<br>}</pre><p>now finally we need to create some UI form from which users can send mail. For this, Create a contact.js file in the pages folder of your app and add the following code to it.</p><pre>import React, { useState } from &quot;react&quot;;<br>import MailOutlineIcon from &quot;@material-ui/icons/MailOutline&quot;;<br>import { MenuItem, Input } from &quot;@material-ui/core&quot;;<br>import TextField from &quot;@material-ui/core/TextField&quot;;<br>import https from &quot;https&quot;;<br><br>function contact() {<br>  const [formError, setFormError] = useState({ error: &quot;&quot; });<br>  const [querySubject, setQuerySetsubject] = useState(&quot;&quot;);<br>  const [name_, setName_] = useState(&quot;&quot;);<br>  const [clientEmail, setClientEmail] = useState(&quot;&quot;);<br>  const [clientMsg, setClientMsg] = useState(&quot;&quot;);<br><br>  const serviceOptions = [<br>    {<br>      value: &quot;option1&quot;,<br>      label: &quot;option1&quot;,<br>    },<br>    {<br>      value: &quot;option2&quot;,<br>      label: &quot;option2&quot;,<br>    },<br>    {<br>      value: &quot;option3&quot;,<br>      label: &quot;option3&quot;,<br>    },<br>    {<br>      value: &quot;option4&quot;,<br>      label: &quot;option4&quot;,<br>    },<br>  ];<br><br>  const sendMail = async (<br>    client_name,<br>    client_email,<br>    client_message,<br>    client_subject<br>  ) =&gt; {<br>    const data = JSON.stringify({<br>      name_: client_name,<br>      email: client_email,<br>      client_message: client_message,<br>      subject: client_subject,<br>    });<br><br>    const options = {<br>      path: &quot;/api/sendMail&quot;,<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;Content-Length&quot;: data.length,<br>      },<br>    };<br><br>    const req = https.request(options, (res) =&gt; {<br>      // console.log(`statusCode: ${res.statusCode}`);<br><br>      res.on(&quot;data&quot;, (d) =&gt; {<br>        // process.stdout.write(d);<br>        // console.log(&quot;data  from API &gt;&gt; &quot;, JSON.parse(d));<br>      });<br>    });<br><br>    req.on(&quot;error&quot;, (error) =&gt; {<br>      setFormError({<br>        error: &quot;Unable to send your message please try after some time.&quot;,<br>      });<br>    });<br><br>    req.write(data);<br>    req.end();<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;form<br>        style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot;, padding: &quot;50px&quot; }}<br>      &gt;<br>        &lt;Input<br>          style={{ width: &quot;100%&quot;, color: &quot;black&quot; }}<br>          type=&quot;text&quot;<br>          value={name_}<br>          placeholder=&quot;What is your name ?&quot;<br>          onChange={(e) =&gt; setName_(e.target.value)}<br>          required<br>        /&gt;<br>        &lt;Input<br>          style={{ width: &quot;100%&quot;, color: &quot;black&quot; }}<br>          value={clientEmail}<br>          type=&quot;email&quot;<br>          placeholder=&quot;What is your email ?&quot;<br>          onChange={(e) =&gt; setClientEmail(e.target.value)}<br>          required<br>        /&gt;<br>        &lt;TextField<br>          style={{ width: &quot;100%&quot;, color: &quot;black&quot; }}<br>          id=&quot;standard-select-Interest&quot;<br>          select<br>          label=&quot;What are you interested in ?&quot;<br>          value={querySubject}<br>          onChange={(e) =&gt; setQuerySetsubject(e.target.value)}<br>          required<br>        &gt;<br>          {serviceOptions.map((option) =&gt; (<br>            &lt;MenuItem key={option.value} value={option.value}&gt;<br>              {option.label}<br>            &lt;/MenuItem&gt;<br>          ))}<br>        &lt;/TextField&gt;<br><br>        &lt;TextField<br>          style={{ width: &quot;100%&quot;, color: &quot;black&quot; }}<br>          id=&quot;client-message-textarea&quot;<br>          label=&quot;Message&quot;<br>          multiline<br>          rows={4}<br>          value={clientMsg}<br>          onChange={(e) =&gt; setClientMsg(e.target.value)}<br>        /&gt;<br>        {formError.error ? (<br>          &lt;div className=&quot;form__error&quot;&gt;<br>            &lt;span style={{ color: &quot;black&quot; }}&gt;{formError.error}&lt;/span&gt;<br>          &lt;/div&gt;<br>        ) : (<br>          &quot;&quot;<br>        )}<br>        &lt;div&gt;<br>          &lt;button<br>            disabled={!name_ || !clientEmail || !clientMsg || !querySubject}<br>            type=&quot;submit&quot;<br>            style={<br>              !name_ || !clientEmail || !clientMsg || !querySubject<br>                ? {<br>                    backgroundColor: &quot;#878a8f&quot;,<br>                    color: &quot;white&quot;,<br>                    transform: &quot;scale(1)&quot;,<br>                    cursor: &quot;default&quot;,<br>                    margin: &quot;50px 0&quot;,<br>                  }<br>                : { margin: &quot;50px 0&quot; }<br>            }<br>            onClick={(e) =&gt; {<br>              e.preventDefault();<br>              sendMail(name_, clientEmail, clientMsg, querySubject);<br>            }}<br>          &gt;<br>            &lt;MailOutlineIcon /&gt; Send<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default contact;</pre><p>And that’s all folks you have a full-featured contact form from which you can send or receive emails.</p><p>I have implemented this in the contact form of my portfolio, which you can try out at my <a href="https://www.lalitvavdara.me/contact">Portfolio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b2e5ce8d741" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>