<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Backend Development - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Backend Development - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 18 May 2026 10:47:21 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/backend-development/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use WebSockets: From Python to FastAPI ]]>
                </title>
                <description>
                    <![CDATA[ Real-time data powers much of modern software: live stock prices, chat applications, sports scores, collaborative tools. And to build these systems, you'll need to understand how real-time communicati ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-websockets-from-python-to-fastapi/</link>
                <guid isPermaLink="false">69b206806c896b0519d2a308</guid>
                
                    <category>
                        <![CDATA[ websockets ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ FastAPI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Real Time ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nneoma Uche ]]>
                </dc:creator>
                <pubDate>Thu, 12 Mar 2026 00:19:12 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/8acb0854-7289-4794-8f97-242ec5d8ca61.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Real-time data powers much of modern software: live stock prices, chat applications, sports scores, collaborative tools. And to build these systems, you'll need to understand how real-time communication actually works—which isn’t always straightforward.</p>
<p>I ran into this firsthand while trying to build a live options dashboard. HTTP requests weren't going to cut it, and everything I was reading seemed overly complex until I went back to the basics. This article is the result of that process.</p>
<p>We'll cover Python's <code>websockets</code> library from scratch, then move into FastAPI, where many Python backends live. It's worth noting that WebSockets aren't the only solution for real-time communication. WebRTC may be a better fit depending on your use case, but understanding WebSockets is the right starting point before exploring further.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a href="#heading-websocket-connections-and-methods">WebSocket Connections and Methods</a></p>
</li>
<li><p><a href="#heading-how-to-build-your-first-websocket-in-python">How to Build Your First WebSocket in Python</a></p>
</li>
<li><p><a href="#heading-file-transfer-over-websockets">File Transfer Over WebSockets</a></p>
</li>
<li><p><a href="#heading-how-to-connect-to-an-external-websocket">How to Connect to an External WebSocket</a></p>
</li>
<li><p><a href="#heading-websockets-in-fastapi">WebSockets in FastAPI</a></p>
</li>
<li><p><a href="#heading-how-to-handle-websocket-disconnections-in-fastapi">How to Handle WebSocket Disconnections in FastAPI</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-websocket-connections-and-methods">WebSocket Connections and Methods</h2>
<p>A WebSocket connection enables bi-directional communication between a client and a server. Once a connection is established, both sides can communicate freely without either having to ask first. This is different from a regular HTTP request, where the client always has to ask before the server can respond.</p>
<p>It looks something like this:</p>
<pre><code class="language-plaintext">        CLIENT&nbsp; &lt;===== open connection =====&gt;&nbsp; SERVER
</code></pre>
<p>Note that a WebSocket URL is not a regular web page, so you can't "visit it" like a website. You need a client to talk to it.</p>
<p>Different frameworks provide different methods for handling WebSocket connections. With Python’s <code>websockets</code> library, for instance, a connection is automatically accepted the moment a client connects. With frameworks like FastAPI, you have to explicitly call <code>await websocket.accept()</code>, otherwise the connection gets rejected.</p>
<p>Let’s look at the core methods provided by Python’s <code>websockets</code> library:</p>
<ol>
<li><p><code>websockets.serve(...)</code>:&nbsp; starts a WebSocket server.</p>
</li>
<li><p><code>websockets.connect(...)</code>: connects to a WebSocket server.</p>
</li>
<li><p><code>websockets.send(...)</code>: sends a message from either side.</p>
</li>
<li><p><code>websockets.recv()</code>: receives a message from client or server.</p>
</li>
</ol>
<p><code>recv()</code> takes no arguments because it's purely a waiting operation. It waits for the next message and returns it:</p>
<pre><code class="language-python">message = await websocket.recv()
</code></pre>
<h2 id="heading-how-to-build-your-first-websocket-in-python">How to Build Your First WebSocket in Python</h2>
<p>Before we dive into frameworks, let’s explore Python’s <code>websockets</code> library. You’ll set up a simple server and client, and exchange messages over a WebSocket connection, giving you a solid foundation for understanding WebSockets under the hood.</p>
<h3 id="heading-environment-setup">Environment Setup</h3>
<p>Run the following in your virtual environment to install or verify the WebSockets package:</p>
<pre><code class="language-python">pip install websockets
# or, to check if it's already installed:
pip show websockets
</code></pre>
<h3 id="heading-create-the-websocket-server">Create the WebSocket Server</h3>
<p>Create <code>server.py</code> in your project folder, and paste this:</p>
<pre><code class="language-python">import asyncio
import websockets

async def handler(connection):
    print("Client connected")

    message = await connection.recv()
    print("Received from client:", message)
    await connection.send("Hello client!")


async def main():
    async with websockets.serve(handler, "localhost", 8000):
        print("Server running at ws://localhost:8000")
        #await asyncio.Future()  # runs forever
        await asyncio.sleep(30)

asyncio.run(main())
</code></pre>
<p>When this line executes:</p>
<pre><code class="language-python">async with websockets.serve(handler, "localhost", 8000):
</code></pre>
<p>The library opens a TCP socket on the specified host and port and waits for incoming clients. When one connects, it creates a connection object and passes it into your handler function.</p>
<p>The handler is required because it defines what the server does with each connection. The <code>host</code> and <code>port</code> arguments are also important. Both default to <code>None</code> – passing neither raises an error because the OS cannot bind a network server without a port.</p>
<p>You could pass <code>port=0</code> to let the OS assign a free port automatically, but then you'd need an extra step to figure out which port was chosen, so the client can connect:</p>
<pre><code class="language-python">server.sockets[0].getsockname()
</code></pre>
<p>It’s simpler to specify both host and port explicitly, so the client knows exactly where the server is running.</p>
<h3 id="heading-set-up-the-client">Set Up the Client</h3>
<p>Create <code>client.py</code> in the same folder and add this:</p>
<pre><code class="language-python">import asyncio
import websockets

async def client():
    async with websockets.connect("ws://localhost:8000") as websocket:
        await websocket.send("Hello server!")
        response = await websocket.recv()
        print("Server replied:", response)

asyncio.run(client())
</code></pre>
<h3 id="heading-test-the-connection">Test the Connection</h3>
<p>First, open a terminal and run <code>server.py</code>. You should see:</p>
<pre><code class="language-plaintext">Server running at ws://localhost:8000
</code></pre>
<p>In a second terminal, run <code>client.py</code>. Messages should appear in both terminals confirming that the connection is active and both sides are communicating.</p>
<p>Note that the server must be running before you start the client – otherwise the client has nothing to connect to, and the connection will fail.</p>
<h4 id="heading-keeping-the-server-alive-a-note-on-asynciofuture">Keeping the server alive: a note on asyncio.Future()</h4>
<p>In <code>server.py</code>, there’s a line currently commented out:</p>
<pre><code class="language-python">await asyncio.Future()
</code></pre>
<p>This keeps the server running indefinitely. For local development and testing however, <code>await asyncio.sleep(30)</code> is a simpler alternative. It keeps the server alive for a fixed period without running forever.</p>
<h2 id="heading-file-transfer-over-websockets">File Transfer Over WebSockets</h2>
<p>WebSockets aren't limited to text. They support raw bytes too, which means you can send files directly over the connection. Here’s how a client can send a file to a server over a WebSocket connection:</p>
<h3 id="heading-update-serverpy">Update <code>server.py</code></h3>
<pre><code class="language-python">async def file_handler(ws):
    print("Client connected, waiting for file...")
    file_bytes = await ws.recv()  # receive bytes
    with open("received_file.png", "wb") as f:
        f.write(file_bytes)
    print("File received and saved!")
    await ws.send("File received successfully!")

async def main():
    async with websockets.serve(file_handler, "localhost", 8000):
        print("Server running on ws://localhost:8000")
        await asyncio.sleep(50)  # keep server alive

asyncio.run(main())
</code></pre>
<p>The handler waits for incoming bytes with <code>await ws.recv()</code>; the <code>websockets</code> library automatically detects whether the incoming message is text or bytes, so no extra configuration is needed. Once received, the file is written to disk in binary mode (<code>"wb"</code>) and the server sends a confirmation message back to the client.</p>
<h3 id="heading-update-clientpy">Update <code>client.py</code></h3>
<pre><code class="language-python">import asyncio
import websockets

async def send_file():
    uri = "ws://localhost:8000"
    async with websockets.connect(uri) as ws:
        with open("portfolio-image.png", "rb") as f:  #open file in binary mode
            file_bytes = f.read()
        await ws.send(file_bytes)  # send bytes
        response = await ws.recv()
        print("Server response:", response)

asyncio.run(send_file())
</code></pre>
<p>The client opens the image in binary mode (<code>"rb"</code>), reads the entire file into memory as bytes, and sends it in a single <code>ws.send()</code> call. It then waits for the server's confirmation before closing the connection.</p>
<h3 id="heading-test-it">Test it</h3>
<p>Add an image to your project folder and make sure the filename in <code>client.py</code> matches. Run <code>server.py</code> first, then <code>client.py</code> in a second terminal.</p>
<p>Once the transfer completes, the server saves the file as <code>received_file.png</code> in the same directory. You should see it appear in your workspace immediately.</p>
<p>This approach loads the entire file into memory before sending. For large files, it’s better to read and send them in chunks. But this is the easiest way to understand WebSocket byte transfer.</p>
<h2 id="heading-how-to-connect-to-an-external-websocket">How to Connect to an External WebSocket</h2>
<p>So far you've been connecting to servers you built yourself. But WebSocket clients can also connect to public servers. For example, a client can connect to Postman’s echo server:</p>
<pre><code class="language-python">import asyncio
import websockets

async def connect_external():
    uri = "wss://ws.postman-echo.com/raw"  # public WebSocket server
    async with websockets.connect(uri) as ws:
        print("Connected to external server!")

        # Send a message
        await ws.send("Hello external server!")
        print("Message sent")

        # Receive response
        response = await ws.recv()
        print("Received from server:", response)
asyncio.run(connect_external())
</code></pre>
<p>Notice the client connects to Postman’s echo server using the <code>wss://</code> URI scheme instead of <code>ws://</code>. This indicates the connection is encrypted using TLS, similar to how <code>https://</code> secures regular web requests.</p>
<p>An echo server returns exactly what you send it. So "Hello external server!" comes straight back as the response. It's a useful sandbox for testing your client-side WebSocket code without needing your own server.</p>
<h2 id="heading-websockets-in-fastapi">WebSockets in FastAPI</h2>
<p>FastAPI provides a WebSocket object (via Starlette under the hood) to manage real-time connections. You can define WebSocket endpoints just like HTTP routes, while Uvicorn handles the event loop – no manual asyncio server management needed. This makes FastAPI a natural fit for real-time projects, from chat apps to live dashboards and data feeds.</p>
<p>Before jumping into code, here's a quick reference of the core methods you'll be working with.</p>
<p><strong>Accepting:</strong></p>
<ul>
<li><code>await websocket.accept()</code>: the <code>accept()</code> method must be called first, before anything else. Skip it and the connection gets rejected.</li>
</ul>
<p><strong>Sending:</strong></p>
<ul>
<li><p><code>await websocket.send_text(data)</code>: sends a string.</p>
</li>
<li><p><code>await websocket.send_bytes(data)</code>: sends binary data.</p>
</li>
<li><p><code>await websocket.send_json(data)</code>: serializes and sends JSON.</p>
</li>
</ul>
<p><strong>Receiving:</strong></p>
<ul>
<li><p><code>await websocket.receive_text()</code>: waits for a text message.</p>
</li>
<li><p><code>await websocket.receive_bytes()</code>: waits for binary data.</p>
</li>
<li><p><code>await websocket.receive_json()</code>: receives and deserializes JSON.</p>
</li>
<li><p><code>async for msg in websocket.iter_text()</code>: iterates over incoming messages, exits cleanly on disconnect.</p>
</li>
</ul>
<p><strong>Closing:</strong></p>
<ul>
<li><code>await websocket.close(code=1000)</code>: standard code for a normal closure. It accepts an optional “reason” argument.</li>
</ul>
<p>Here's what the WebSocket lifecycle looks like in FastAPI:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6426acfa5bc738c37852b5bd/b61b6b25-e027-47a1-8efc-b921e93b8521.png" alt="WebSocket in FastAPI" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<h3 id="heading-building-a-simple-echo-server-with-fastapi">Building a Simple Echo Server with FastAPI</h3>
<p>As you saw with the Postman example, an echo server sends back the message a client provides. Let's build one with FastAPI.</p>
<h4 id="heading-1-install-fastapi">1. Install FastAPI:</h4>
<pre><code class="language-python">pip install "fastapi[standard]"
</code></pre>
<h4 id="heading-2-update-serverpy">2. Update <code>server.py</code>:</h4>
<pre><code class="language-python">from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    data = await websocket.receive_text()
   
    await websocket.send_text(f"You said: {data}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)
</code></pre>
<p>A few things to note here compared to the plain <code>websockets</code> library:</p>
<ul>
<li><p>WebSocket endpoints are defined with <code>@app.websocket("/ws")</code> just like an HTTP route.</p>
</li>
<li><p><code>await websocket.accept()</code> is required before anything else. FastAPI won't accept connections without it.</p>
</li>
<li><p>Uvicorn handles the event loop and server startup for you via the <code>if name == "__main__"</code> block. No <code>asyncio.run()</code> or <code>asyncio.Future()</code> needed.</p>
</li>
</ul>
<h4 id="heading-3-update-clientpy">3. Update client.py:</h4>
<pre><code class="language-python">async def test_client():
    uri = "ws://127.0.0.1:8000/ws"
    async with websockets.connect(uri) as ws:
        await ws.send("Hello FastAPI server!")
        response = await ws.recv()
        print("Server replied:", response)

asyncio.run(test_client())
</code></pre>
<p>Since the FastAPI server isn't secured with TLS, the client URI uses <code>ws://</code> instead of <code>wss://</code>. Make sure to match the host and port from your server code.</p>
<h4 id="heading-4-interact-with-the-echo-server">4. Interact with the echo server:</h4>
<p>Start <code>server.py</code>, then run <code>client.py</code> in another terminal. The server terminal should show the echoed message.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6426acfa5bc738c37852b5bd/88629d79-eb91-4af5-9752-f9596ff5e5a4.png" alt="88629d79-eb91-4af5-9752-f9596ff5e5a4" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<h2 id="heading-how-to-handle-websocket-disconnections-in-fastapi">How to Handle WebSocket Disconnections in FastAPI</h2>
<p>Clients will inevitably disconnect in real-time applications, sometimes intentionally, sometimes unexpectedly. If not handled properly, this can crash your server or leave it in a broken state.</p>
<p>The <code>WebSocketDisconnect</code> exception in FastAPI is raised whenever a client unexpectedly closes the connection, allowing the server to handle disconnects gracefully, log the event, and clean up resources without crashing.</p>
<p>Here’s an example:</p>
<pre><code class="language-python">@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
    await ws.accept()
    try:
        while True:
            data = await ws.receive_text()
   
            if "bye" in data or "quit" in data:
                await ws.send_text("Closing connection")
                await ws.close(code=1000, reason="Server requested close")  
                break
            await ws.send_text(f"I got your request: {data}")
    except WebSocketDisconnect:
        print("Client disconnected")  # connection already closed
</code></pre>
<p>The server runs a continuous loop waiting for messages. If the client message contains "bye" or "quit", the server responds, calls <code>await ws.close(code=1000)</code>, and breaks out of the loop cleanly.</p>
<p>But if the client disconnects unexpectedly, <code>WebSocketDisconnect</code> is caught by the except block and the server moves on without crashing. At this point the connection is already closed on the client side, so calling <code>ws.close()</code> inside the except block is unnecessary.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>WebSockets make real-time communication possible by keeping a persistent connection open between client and server. Starting with Python’s <code>websockets</code> library helps clarify how the protocol works under the hood, while frameworks like FastAPI provide the structure needed for production applications.</p>
<p>The parts that trip most people up early on are <code>asyncio</code> and FastAPI's explicit <code>websocket.accept()</code>. With <code>asyncio</code>, the question is usually why it's needed and why the server dies instantly without something keeping it alive. And it's easy to ignore <code>websocket.accept()</code> if you're coming from the plain <code>websockets library</code> where that happens automatically. Once those click, everything else follows naturally.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Intro to Backend Web Development – Node.js, Express, MongoDB ]]>
                </title>
                <description>
                    <![CDATA[ Backend development involves building the server-side "brain" of a website that manages user data, authentication, and database communication. We just posted a course on the freeCodeCamp.org YouTube channel that will teach you how to construct a basi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/intro-to-backend-web-development-nodejs-express-mongodb/</link>
                <guid isPermaLink="false">691b3887dbd8303d75f4137c</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Mon, 17 Nov 2025 15:00:23 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1763372629451/d682e5f7-31d1-48af-8957-8e916b7b506a.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Backend development involves building the server-side "brain" of a website that manages user data, authentication, and database communication.</p>
<p>We just posted a course on the freeCodeCamp.org YouTube channel that will teach you how to construct a basic backend for a website using popular technologies like Node.js, Express.js, and the MongoDB NoSQL database.</p>
<p>The tutorial covers the core components of backend development, walking you through the initial server setup, database connection, and code structure using a model, route, and controller pattern.</p>
<p>You will learn to build practical APIs for user authentication, including password hashing, as well as full CRUD (Create, Read, Update, Delete) operations to manage data. Finally, the video demonstrates how to utilize Postman to test your server's requests and ensure your APIs are functioning correctly.</p>
<p>This course was developed by Shivani. She is part of Hack Club. Hack Club is a global non-profit organization that creates a community for high school students interested in coding and making things with technology.</p>
<p>Here are the sections covered in this course:</p>
<ul>
<li><p>Introduction &amp; Overview</p>
</li>
<li><p>What is a Backend?</p>
</li>
<li><p>Core Components: Languages, Databases, Runtimes, Frameworks</p>
</li>
<li><p>Backend Architecture Flowchart</p>
</li>
<li><p>How Frontend Connects to Backend (APIs)</p>
</li>
<li><p>Prerequisites &amp; Installing Node.js</p>
</li>
<li><p>Project Folder Structure</p>
</li>
<li><p>Project Initialization (Git &amp; npm)</p>
</li>
<li><p>Setting up MongoDB Atlas Database</p>
</li>
<li><p>Environment Variables (.env)</p>
</li>
<li><p>Constants &amp; ES Modules Setup</p>
</li>
<li><p>Creating the Express App (app.js)</p>
</li>
<li><p>Connecting Database to Server (database.js)</p>
</li>
<li><p>Server Entry Point (index.js)</p>
</li>
<li><p>Setting up Nodemon &amp; Running the Server</p>
</li>
<li><p>Understanding Models &amp; ER Diagrams</p>
</li>
<li><p>Creating the User Model</p>
</li>
<li><p>Understanding Routes</p>
</li>
<li><p>Setting up User Routes</p>
</li>
<li><p>Understanding Controllers</p>
</li>
<li><p>Coding the Register Controller</p>
</li>
<li><p>The Journey of a Request</p>
</li>
<li><p>HTTP Methods &amp; Status Codes Explained</p>
</li>
<li><p>Introduction to Postman</p>
</li>
<li><p>Testing the Register API</p>
</li>
<li><p>Viewing Data in MongoDB Atlas</p>
</li>
<li><p>Coding the Login Controller</p>
</li>
<li><p>Hashing Passwords with Bcrypt</p>
</li>
<li><p>Comparing Passwords for Login</p>
</li>
<li><p>Testing the Login API</p>
</li>
<li><p>Coding the Logout Controller</p>
</li>
<li><p>Testing the Logout API</p>
</li>
<li><p>Intro to CRUD APIs</p>
</li>
<li><p>Creating the Post Model</p>
</li>
<li><p>Create Post API (Controller &amp; Route)</p>
</li>
<li><p>Testing Create Post</p>
</li>
<li><p>Read All Posts API</p>
</li>
<li><p>Testing Get Posts</p>
</li>
<li><p>Update Post API</p>
</li>
<li><p>Testing Update Post</p>
</li>
<li><p>Delete Post API</p>
</li>
<li><p>Testing Delete Post</p>
</li>
<li><p>Final Commit &amp; Conclusion</p>
</li>
</ul>
<p>Watch the full course on the <a target="_blank" href="https://youtu.be/KOutPbKc9UM">freeCodeCamp.org YouTube channel</a> (2-hour watch),.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/KOutPbKc9UM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Extend CRUD Operations to Align with Business Workflows ]]>
                </title>
                <description>
                    <![CDATA[ Most developers are introduced to databases and APIs through a simple pattern: CRUD—Create, Read, Update, Delete. It seems like the perfect abstraction. With just four operations, you can model almost anything. Tutorials use it. Frameworks generate i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/extend-crud-operations-to-align-with-business-workflows/</link>
                <guid isPermaLink="false">68c19bc01159a9ac851f6cb5</guid>
                
                    <category>
                        <![CDATA[ crud ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tim Kleier ]]>
                </dc:creator>
                <pubDate>Wed, 10 Sep 2025 15:39:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757518255485/8e727e36-d22a-42d9-b1a7-98d3ca5eae35.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most developers are introduced to databases and APIs through a simple pattern: CRUD—Create, Read, Update, Delete. It seems like the perfect abstraction. With just four operations, you can model almost anything. Tutorials use it. Frameworks generate it. We teach it to beginners as the foundation of working with data.</p>
<p>But once you move beyond basic apps, CRUD starts to fall apart.</p>
<p>Real-world systems don’t just “update” or “delete” things. In a loan application system, for example, borrowers “submit” applications, loan officers “approve” or “reject” them, and applications are eventually “archived”. These aren’t generic CRUD operations—they’re <strong>domain-specific actions</strong> that carry meaning.</p>
<p>And that’s the problem: CRUD hides the meaning of our systems behind vague verbs. REST APIs inherit the same issue, mapping HTTP verbs onto CRUD but still failing to express real workflows clearly.</p>
<p>In this article, we’ll explore:</p>
<ul>
<li><p>Why CRUD works fine for simple apps but becomes an anti-pattern at scale</p>
</li>
<li><p>How concepts like <strong>upsert</strong>, <strong>archive</strong>, and <strong>bulk operations</strong> reveal its cracks</p>
</li>
<li><p>Why REST doesn’t solve these issues</p>
</li>
<li><p>How to design APIs around domain actions and workflows instead.</p>
</li>
</ul>
<p>By the end, you’ll see CRUD for what it really is—a teaching tool, not a design philosophy.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-crud">What is CRUD?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-stretching-crud-upsert-archive-bulk">Stretching CRUD: Upsert, Archive, Bulk</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-breaking-crud-domain-actions">Breaking CRUD: Domain Actions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-breaking-crud-domain-authorization">Breaking CRUD: Domain Authorization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-crud-alternative-align-to-workflows">CRUD Alternative: Align to Workflows</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-crud">What is CRUD?</h2>
<p><strong>Create, Read, Update, Delete</strong>—these are the four basic operations we perform on data in a database.</p>
<ul>
<li><p><strong>Create</strong> – adds a new record.</p>
</li>
<li><p><strong>Read</strong> – fetches an existing record (or list of records).</p>
</li>
<li><p><strong>Update</strong> – changes one or more fields in a record.</p>
</li>
<li><p><strong>Delete</strong> – removes a record.</p>
</li>
</ul>
<p>For example, in a typical Node.js + Express app managing users:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create a user</span>
app.post(<span class="hljs-string">'/users'</span>, createUser);

<span class="hljs-comment">// Read a user</span>
app.get(<span class="hljs-string">'/users/:id'</span>, getUser);

<span class="hljs-comment">// Update a user</span>
app.put(<span class="hljs-string">'/users/:id'</span>, updateUser);

<span class="hljs-comment">// Delete a user</span>
app.delete(<span class="hljs-string">'/users/:id'</span>, deleteUser);
</code></pre>
<p>This maps directly to the underlying SQL:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span> (...);
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = ...;
<span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">SET</span> ... <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = ...;
<span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = ...;
</code></pre>
<p>And that’s CRUD in its purest form—four operations that can describe almost any database interaction.</p>
<h2 id="heading-stretching-crud-upsert-archive-bulk">Stretching CRUD: Upsert, Archive, Bulk</h2>
<p>Developers quickly realize CRUD isn’t enough, so they invent extensions:</p>
<ul>
<li><p><strong>Upsert</strong>: a mix of “update” and “insert.” If the record exists, update it; if not, create it.</p>
</li>
<li><p><strong>Archive</strong>: instead of deleting a record, we “soft delete” or mark it as inactive so the history stays intact.</p>
</li>
<li><p><strong>Bulk operations</strong>: run create, update, or delete on many records at once for efficiency.</p>
</li>
</ul>
<p>These solve real problems, but they stretch CRUD’s simple model. We now need to distinguish between single and bulk resource actions. And we also need to factor in the technical concerns of upsertions and soft deletions.</p>
<h2 id="heading-breaking-crud-domain-actions">Breaking CRUD: Domain Actions</h2>
<p>The technical domain itself stretches CRUD substantially, but business domain concerns break it entirely. Take a loan application system:</p>
<ul>
<li><p>A borrower doesn’t “create” and “update” an application—they start, submit, or withdraw it.</p>
</li>
<li><p>A loan officer doesn’t “update” an application—they review, approve, or reject it.</p>
</li>
<li><p>Applications don’t get “deleted”—they’re usually archived so there’s a record for compliance.</p>
</li>
</ul>
<p>If we try to model these as plain CRUD, the meaning gets lost:</p>
<pre><code class="lang-http"><span class="hljs-attribute">PATCH /applications/123 { "status"</span>: "approved" }
</code></pre>
<p>Technically, it works. But what does “update” really mean here? Was the application submitted, rejected, or archived? You can’t tell from the API call.</p>
<p>The core problem: CRUD hides intent behind generic, technical language. Real business processes are expressed as domain-specific actions, not generic updates or deletes.</p>
<h2 id="heading-breaking-crud-domain-authorization">Breaking CRUD: Domain Authorization</h2>
<p>CRUD not only obscures intent—it also creates authorization gaps. Using the same loan application example:</p>
<ul>
<li><p>Only loan officers should approve applications.</p>
</li>
<li><p>Borrowers should only edit their own information or withdraw their applications.</p>
</li>
</ul>
<p>If “approve” is just modeled as a generic update, the system can’t distinguish between roles without additional checks. A naive authorization rule like “can this user update?” suddenly lets borrowers perform actions reserved for officers.</p>
<p>This mismatch between technical verbs and business rules can lead to:</p>
<ul>
<li><p>Security issues—unauthorized actions performed by the wrong user.</p>
</li>
<li><p>Audit problems—it’s unclear who did what, and when.</p>
</li>
<li><p>Workflow confusion—state transitions get lost in generic updates.</p>
</li>
</ul>
<p>The solution: treat each domain action as its own API call with explicit authorization rules:</p>
<pre><code class="lang-http"><span class="hljs-attribute">POST /applications/123/approve   # Only accessible to loan officers
POST /applications/123/withdraw  # Only accessible to the borrower</span>
</code></pre>
<p>By modeling actions instead of CRUD operations, intent and permissions are clear, reducing both bugs and security risks.</p>
<h2 id="heading-crud-alternative-align-to-workflows">CRUD Alternative: Align to Workflows</h2>
<p>Real-world applications follow workflows—sequences of states that a resource moves through. Take our loan application example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1757257665063/f26ce4c4-afee-4b03-8ddc-bdb724aa9850.png" alt="Loan Application Workflow Diagram" class="image--center mx-auto" width="681" height="674" loading="lazy"></p>
<p>Here’s what the corresponding API endpoints might look like:</p>
<pre><code class="lang-http"># Borrower actions
<span class="hljs-attribute">POST /applications/123/submit       # Draft → Submitted
POST /applications/123/withdraw     # Draft/Submitted → Closed

# Loan officer actions
POST /applications/123/approve      # Submitted → Approved
POST /applications/123/reject       # Submitted → Rejected

# System/Admin actions
POST /applications/123/close        # Approved/Rejected → Closed

# Side effect</span>: spawning a Loan (after Approved)
<span class="hljs-attribute">POST /loans
{
  "applicationId"</span>: "123",
  "amount": 50000,
  "borrowerId": "456",
  "terms": { ... }
}
</code></pre>
<p>At this point, our API calls are almost entirely outside the CRUD pattern—the only one that resembles a CRUD action is the spawning of a loan, which looks like a “create”. Behind the scenes, we’ll still use <code>INSERT</code>, <code>SELECT</code>, and <code>UPDATE</code> statements in SQL, but at the API level we’re aligning to the actual business workflow. Because of it, we’re able to easily support the following:</p>
<ol>
<li><p><strong>Actions reflect business intent</strong> — each API call maps to a real-world task like submit, approve, or withdraw.</p>
</li>
<li><p><strong>Built-in authorization</strong> — endpoints clearly separate borrower, loan officer, and admin responsibilities.</p>
</li>
<li><p><strong>Auditability and workflow enforcement</strong> — state transitions are explicit and invalid transitions are prevented.</p>
</li>
<li><p><strong>Controlled side effects</strong> — spawning loans, notifications, and downstream processes are handled deliberately.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By moving away from CRUD and modeling domain actions instead, our API aligns with real business workflows, clearly communicates intent, and enforces rules and authorization naturally. State transitions, side effects, and auditing become explicit, reducing errors and security risks. While CRUD still powers the underlying database operations, thinking in terms of actions and workflows ensures that the system behaves the way the business expects.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build Multi-Module Projects in Spring Boot for Scalable Microservices ]]>
                </title>
                <description>
                    <![CDATA[ As software applications grow in complexity, managing scalability, modularity, and clarity becomes essential. Spring Boot’s multi-module structure allows you to manage different parts of the application independently, which lets your team develop, te... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-multi-module-projects-in-spring-boot-for-scalable-microservices/</link>
                <guid isPermaLink="false">6733855c0e235bf7a79c5c4f</guid>
                
                    <category>
                        <![CDATA[ Spring Boot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Microservices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ maven ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ scalability ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Birkaran Sachdev ]]>
                </dc:creator>
                <pubDate>Tue, 12 Nov 2024 16:42:04 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/uyfohHiTxho/upload/716c6610c336976df67b833912170336.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As software applications grow in complexity, managing scalability, modularity, and clarity becomes essential.</p>
<p>Spring Boot’s multi-module structure allows you to manage different parts of the application independently, which lets your team develop, test, and deploy components separately. This structure keeps code organized and modular, making it useful for both microservices and large monolithic systems.</p>
<p>In this tutorial, you’ll build a multi-module Spring Boot project, with each module dedicated to a specific responsibility. You’ll learn how to set up modules, configure inter-module communication, handle errors, implement JWT-based security, and deploy using Docker.</p>
<p><strong>Prerequisites</strong>:</p>
<ul>
<li><p>Basic knowledge of Spring Boot and Maven.</p>
</li>
<li><p>Familiarity with Docker and CI/CD concepts (optional but helpful).</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-1-why-multi-module-projects">Why Multi-Module Projects?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-project-structure-and-architecture">Project Structure and Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-how-to-set-up-the-parent-project">How to Set Up the Parent Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-how-to-create-the-modules">How to Create the Modules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-inter-module-communication">Inter-Module Communication</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-common-pitfalls-and-solutions">Common Pitfalls and Solutions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-testing-strategy">Testing Strategy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-error-handling-and-logging">Error Handling and Logging</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-security-and-jwt-integration">Security and JWT Integration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-deployment-with-docker-and-cicd">Deployment with Docker and CI/CD</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-11-best-practices-and-advanced-use-cases">Best Practices and Advanced Use Cases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-12-conclusion-and-key-takeaways">Conclusion and Key Takeaways</a></p>
</li>
</ol>
<h2 id="heading-1-why-multi-module-projects">1. Why Multi-Module Projects?</h2>
<p>In single-module projects, components are often tightly coupled, making it difficult to scale and manage complex codebases. A multi-module structure offers several advantages:</p>
<ul>
<li><p><strong>Modularity</strong>: Each module is dedicated to a specific task, such as User Management or Inventory, simplifying management and troubleshooting.</p>
</li>
<li><p><strong>Team Scalability</strong>: Teams can work independently on different modules, minimizing conflicts and enhancing productivity.</p>
</li>
<li><p><strong>Flexible Deployment</strong>: Modules can be deployed or updated independently, which is particularly beneficial for microservices or large applications with numerous features.</p>
</li>
</ul>
<h3 id="heading-real-world-example"><strong>Real-World Example</strong></h3>
<p>Consider a large e-commerce application. Its architecture can be divided into distinct modules:</p>
<ul>
<li><p><strong>Customer Management</strong>: Responsible for handling customer profiles, preferences, and authentication.</p>
</li>
<li><p><strong>Product Management</strong>: Focuses on managing product details, stock, and pricing.</p>
</li>
<li><p><strong>Order Processing</strong>: Manages orders, payments, and order tracking.</p>
</li>
<li><p><strong>Inventory Management</strong>: Oversees stock levels and supplier orders.</p>
</li>
</ul>
<h3 id="heading-case-study-netflix"><strong>Case Study: Netflix</strong></h3>
<p>To illustrate these benefits, let's examine how Netflix employs a multi-module architecture.</p>
<p>Netflix is a leading example of a company that effectively uses this approach through its microservices architecture. Each microservice at Netflix is dedicated to a specific function, such as user authentication, content recommendations, or streaming services.</p>
<p>This modular structure enables Netflix to scale its operations efficiently, deploy updates independently, and maintain high availability and performance. By decoupling services, Netflix can manage millions of users and deliver content seamlessly worldwide, ensuring a robust and flexible system that supports its vast and dynamic platform.</p>
<p>This architecture not only enhances scalability but also improves fault isolation, allowing Netflix to innovate rapidly and respond effectively to user demands.</p>
<h2 id="heading-2-project-structure-and-architecture">2. Project Structure and Architecture</h2>
<p>Now let’s get back to our example project. Your multi-module Spring Boot project will use five key modules. Here’s the layout:</p>
<pre><code class="lang-plaintext">codespring-boot-multi-module/
 ├── common/               # Shared utilities and constants
 ├── domain/               # Domain entities
 ├── repository/           # Data access layer (DAL)
 ├── service/              # Business logic
 └── web/                  # Main Spring Boot application and controllers
</code></pre>
<p>Each module has a specific role:</p>
<ul>
<li><p><code>common</code>: Stores shared utilities, constants, and configuration files used across other modules.</p>
</li>
<li><p><code>domain</code>: Contains data models for your application.</p>
</li>
<li><p><code>repository</code>: Manages database operations.</p>
</li>
<li><p><code>service</code>: Encapsulates business logic.</p>
</li>
<li><p><code>web</code>: Defines REST API endpoints and serves as the application’s entry point.</p>
</li>
</ul>
<p>This structure aligns with <strong>separation of concerns</strong> principles, where each layer is independent and handles its own logic.</p>
<p>The diagram below illustrates the various modules:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730873719792/adfc3689-26ae-477a-9850-75070a777e5e.png" alt="Diagram showing a software architecture with five modules: Web, Service, Repository, Domain, and Common, connected by arrows indicating relationships." class="image--center mx-auto" width="1306" height="767" loading="lazy"></p>
<h2 id="heading-3-how-to-set-up-the-parent-project">3. How to Set Up the Parent Project</h2>
<h3 id="heading-step-1-create-the-root-project">Step 1: Create the Root Project</h3>
<p>Let’s run these commands to create the Maven parent project:</p>
<pre><code class="lang-bash">mvn archetype:generate -DgroupId=com.example -DartifactId=spring-boot-multi-module -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=<span class="hljs-literal">false</span>
<span class="hljs-built_in">cd</span> spring-boot-multi-module
</code></pre>
<h3 id="heading-step-2-configure-the-parent-pomxml">Step 2: Configure the Parent <code>pom.xml</code></h3>
<p>In the <code>pom.xml</code>, let’s define our dependencies and modules:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0"</span> <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span> <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://maven.apache.org/POM/4.0.0 http://www.apache.org/xsd/maven-4.0.0.xsd"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.example<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-multi-module<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.0-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">packaging</span>&gt;</span>pom<span class="hljs-tag">&lt;/<span class="hljs-name">packaging</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">modules</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>common<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>domain<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>repository<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>service<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">module</span>&gt;</span>web<span class="hljs-tag">&lt;/<span class="hljs-name">module</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">modules</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">java.version</span>&gt;</span>11<span class="hljs-tag">&lt;/<span class="hljs-name">java.version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">spring.boot.version</span>&gt;</span>2.5.4<span class="hljs-tag">&lt;/<span class="hljs-name">spring.boot.version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependencyManagement</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-dependencies<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${spring.boot.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">type</span>&gt;</span>pom<span class="hljs-tag">&lt;/<span class="hljs-name">type</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>import<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencyManagement</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>This <code>pom.xml</code> file centralizes dependencies and configurations, making it easier to manage shared settings across modules.</p>
<h2 id="heading-4-how-to-create-the-modules">4. How to Create the Modules</h2>
<h3 id="heading-common-module">Common Module</h3>
<p>Let’s create a <strong>common</strong> module to define shared utilities like date formatters. Create this module and add a sample utility class:</p>
<pre><code class="lang-bash">mvn archetype:generate -DgroupId=com.example.common -DartifactId=common -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=<span class="hljs-literal">false</span>
</code></pre>
<p><strong>Date Formatter Utility:</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.example.common;

<span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.format.DateTimeFormatter;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DateUtils</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">formatDate</span><span class="hljs-params">(LocalDate date)</span> </span>{
        <span class="hljs-keyword">return</span> date.format(DateTimeFormatter.ofPattern(<span class="hljs-string">"yyyy-MM-dd"</span>));
    }
}
</code></pre>
<h3 id="heading-domain-module">Domain Module</h3>
<p>In the <strong>domain</strong> module, you will define your data models.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.example.domain;

<span class="hljs-keyword">import</span> javax.persistence.Entity;
<span class="hljs-keyword">import</span> javax.persistence.Id;

<span class="hljs-meta">@Entity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-meta">@Id</span>
    <span class="hljs-keyword">private</span> Long id;
    <span class="hljs-keyword">private</span> String name;

    <span class="hljs-comment">// Getters and Setters</span>
}
</code></pre>
<h3 id="heading-repository-module">Repository Module</h3>
<p>Let’s create the <strong>repository</strong> module to manage data access. Here’s a basic repository interface:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.example.repository;

<span class="hljs-keyword">import</span> com.example.domain.User;
<span class="hljs-keyword">import</span> org.springframework.data.jpa.repository.JpaRepository;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">User</span>, <span class="hljs-title">Long</span>&gt; </span>{}
</code></pre>
<h3 id="heading-service-module">Service Module</h3>
<p>Let’s create the <strong>service</strong> module to hold your business logic. Here’s an example service class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.example.service;

<span class="hljs-keyword">import</span> com.example.domain.User;
<span class="hljs-keyword">import</span> com.example.repository.UserRepository;
<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Service;

<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserService</span> </span>{

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserRepository userRepository;

    <span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">getUserById</span><span class="hljs-params">(Long id)</span> </span>{
        <span class="hljs-keyword">return</span> userRepository.findById(id).orElse(<span class="hljs-keyword">null</span>);
    }
}
</code></pre>
<h3 id="heading-web-module">Web Module</h3>
<p>The <strong>web</strong> module serves as the REST API layer.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> </span>{

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserService userService;

    <span class="hljs-meta">@GetMapping("/users/{id}")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">getUserById</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Long id)</span> </span>{
        <span class="hljs-keyword">return</span> userService.getUserById(id);
    }
}
</code></pre>
<h2 id="heading-5-inter-module-communication">5. Inter-Module Communication</h2>
<p>To avoid direct dependencies, you can use <strong>REST APIs</strong> or <strong>message brokers</strong> (like Kafka) for inter-module communication. This ensures loose coupling and allows each module to communicate independently.</p>
<p>The diagram below demonstrates how modules communicate with each other:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730874358819/89d7f058-d074-4b1d-bbb7-81a7bdcb868e.png" alt="Flowchart showing the interaction between modules in the software architecture: Web Module handles API endpoints and returns responses, Service Module executes business logic, Repository Module accesses data and returns processed data, and connects to a Database." class="image--center mx-auto" width="932" height="1263" loading="lazy"></p>
<p>The diagram illustrates how different system components communicate to handle requests efficiently.</p>
<p>The <strong>Web Module</strong> processes incoming API requests and forwards them to the <strong>Service Module</strong>, which contains the business logic. The <strong>Service Module</strong> then interacts with the <strong>Repository Module</strong> to fetch or update data in the <strong>Database</strong>. This layered approach ensures that each module operates independently, promoting flexibility and easier maintenance.</p>
<p><strong>Example Using Feign Client</strong>:</p>
<p>In the context of inter-module communication, using tools like <strong>Feign Clients</strong> is a powerful way to achieve loose coupling between services.</p>
<p>The Feign client allows one module to seamlessly communicate with another through REST API calls, without requiring direct dependencies. This approach fits perfectly within the layered architecture described earlier, where the <strong>Service Module</strong> can fetch data from other services or microservices using Feign clients, rather than directly accessing databases or hard-coding HTTP requests.</p>
<p>This not only simplifies the code but also improves scalability and maintainability by isolating service dependencies.</p>
<pre><code class="lang-java"><span class="hljs-meta">@FeignClient(name = "userServiceClient", url = "http://localhost:8081")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserServiceClient</span> </span>{
    <span class="hljs-meta">@GetMapping("/users/{id}")</span>
    <span class="hljs-function">User <span class="hljs-title">getUserById</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable("id")</span> Long id)</span></span>;
}
</code></pre>
<h2 id="heading-6-common-pitfalls-and-solutions">6. Common Pitfalls and Solutions</h2>
<p>When implementing a multi-module architecture, you may encounter several challenges. Here are some common pitfalls and their solutions:</p>
<ul>
<li><p><strong>Circular Dependencies</strong>: Modules may inadvertently depend on each other, creating a circular dependency that complicates builds and deployments.</p>
<ul>
<li><strong>Solution</strong>: Carefully design module interfaces and use dependency management tools to detect and resolve circular dependencies early in the development process.</li>
</ul>
</li>
<li><p><strong>Over-Engineering</strong>: There's a risk of creating too many modules, leading to unnecessary complexity.</p>
<ul>
<li><strong>Solution</strong>: Start with a minimal set of modules and only split further when there's a clear need, ensuring each module has a distinct responsibility.</li>
</ul>
</li>
<li><p><strong>Inconsistent Configurations</strong>: Managing configurations across multiple modules can lead to inconsistencies.</p>
<ul>
<li><strong>Solution</strong>: Use centralized configuration management tools, such as Spring Cloud Config, to maintain consistency across modules.</li>
</ul>
</li>
<li><p><strong>Communication Overhead</strong>: Inter-module communication can introduce latency and complexity.</p>
<ul>
<li><strong>Solution</strong>: Optimize communication by using efficient protocols and consider asynchronous messaging where appropriate to reduce latency.</li>
</ul>
</li>
<li><p><strong>Testing Complexity</strong>: Testing a multi-module project can be more complex due to the interactions between modules.</p>
<ul>
<li><strong>Solution</strong>: Implement a robust testing strategy that includes unit tests for individual modules and integration tests for inter-module interactions.</li>
</ul>
</li>
</ul>
<p>By being aware of these pitfalls and applying these solutions, you can effectively manage the complexities of a multi-module architecture and ensure a smooth development process.</p>
<h2 id="heading-7-testing-strategy-and-configuration">7. Testing Strategy and Configuration</h2>
<p>Testing each module independently and as a unit is critical in multi-module setups.</p>
<h3 id="heading-unit-tests">Unit Tests</h3>
<p>Here, we’ll use JUnit and Mockito for performing unit tests:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RunWith(MockitoJUnitRunner.class)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserServiceTest</span> </span>{

    <span class="hljs-meta">@Mock</span>
    <span class="hljs-keyword">private</span> UserRepository userRepository;

    <span class="hljs-meta">@InjectMocks</span>
    <span class="hljs-keyword">private</span> UserService userService;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testGetUserById</span><span class="hljs-params">()</span> </span>{
        User user = <span class="hljs-keyword">new</span> User();
        user.setId(<span class="hljs-number">1L</span>);
        user.setName(<span class="hljs-string">"John"</span>);

        Mockito.when(userRepository.findById(<span class="hljs-number">1L</span>)).thenReturn(Optional.of(user));

        User result = userService.getUserById(<span class="hljs-number">1L</span>);
        assertEquals(<span class="hljs-string">"John"</span>, result.getName());
    }
}
</code></pre>
<h3 id="heading-integration-tests">Integration Tests</h3>
<p>And we’ll use Testcontainers with an in-memory database for integration tests:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Testcontainers</span>
<span class="hljs-meta">@ExtendWith(SpringExtension.class)</span>
<span class="hljs-meta">@SpringBootTest</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserServiceIntegrationTest</span> </span>{

    <span class="hljs-meta">@Container</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> PostgreSQLContainer&lt;?&gt; postgresqlContainer = <span class="hljs-keyword">new</span> PostgreSQLContainer&lt;&gt;(<span class="hljs-string">"postgres:latest"</span>);

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserService userService;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testFindById</span><span class="hljs-params">()</span> </span>{
        User user = userService.getUserById(<span class="hljs-number">1L</span>);
        assertNotNull(user);
    }
}
</code></pre>
<h2 id="heading-8-error-handling-and-logging">8. Error Handling and Logging</h2>
<p>Error handling and logging ensure a robust and debuggable application.</p>
<h3 id="heading-error-handling">Error Handling</h3>
<p>In this section, we'll explore how to handle errors gracefully in your Spring Boot application using a <strong>global exception handler</strong>. By using <code>@ControllerAdvice</code>, we'll set up a centralized way to catch and respond to errors, keeping our code clean and our responses consistent.</p>
<pre><code class="lang-java"><span class="hljs-meta">@ControllerAdvice</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GlobalExceptionHandler</span> </span>{

    <span class="hljs-meta">@ExceptionHandler(UserNotFoundException.class)</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity&lt;String&gt; <span class="hljs-title">handleUserNotFoundException</span><span class="hljs-params">(UserNotFoundException ex)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ResponseEntity&lt;&gt;(<span class="hljs-string">"User not found"</span>, HttpStatus.NOT_FOUND);
    }
}
</code></pre>
<p>In the code example above, we define a <code>GlobalExceptionHandler</code> that catches any <code>UserNotFoundException</code> and returns a friendly message like "User not found" with a status of <code>404</code>. This way, you don’t have to handle this exception in every controller—you’ve got it covered in one place!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730874789550/feed75e6-f92c-4102-b3c3-a01f189f3cd7.png" alt="Flowchart depicting a sequence of interactions between a Client, Web Module, Global Error Handler, and Logger. The process involves handling requests, processing them, and managing exceptions. If an exception occurs, it is handled and logged, followed by an error response. If no exception occurs, a successful response is returned." class="image--center mx-auto" width="1617" height="1350" loading="lazy"></p>
<p>Now, let’s take a look at the diagram. Here’s how it all flows: when a client sends a request to our <strong>Web Module</strong>, if everything goes smoothly, you'll get a successful response. But if something goes wrong, like a user not being found, the error will be caught by our <strong>Global Error Handler</strong>. This handler logs the issue and returns a clean, structured response to the client.</p>
<p>This approach ensures that users get clear error messages while keeping your app’s internals hidden and secure.</p>
<h3 id="heading-logging">Logging</h3>
<p>Structured logging in each module improves traceability and debugging. You can use a centralized logging system like Logback and include correlation IDs to trace requests.</p>
<h2 id="heading-9-security-and-jwt-integration">9. Security and JWT Integration</h2>
<p>In this section, we’re going to set up <strong>JSON Web Tokens (JWT)</strong> to secure our endpoints and control access based on user roles. We'll configure this in the <code>SecurityConfig</code> class, which will help us enforce who can access what parts of our application.</p>
<pre><code class="lang-java"><span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebSecurityConfigurerAdapter</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        http.authorizeRequests()
            .antMatchers(<span class="hljs-string">"/admin/**"</span>).hasRole(<span class="hljs-string">"ADMIN"</span>)
            .antMatchers(<span class="hljs-string">"/user/**"</span>).hasAnyRole(<span class="hljs-string">"USER"</span>, <span class="hljs-string">"ADMIN"</span>)
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer().jwt();
    }
}
</code></pre>
<p>In the code example above, you can see how we’ve defined access rules:</p>
<ul>
<li><p>The <code>/admin/**</code> endpoints are restricted to users with the <code>ADMIN</code> role.</p>
</li>
<li><p>The <code>/user/**</code> endpoints can be accessed by users with either the <code>USER</code> or <code>ADMIN</code> roles.</p>
</li>
<li><p>Any other requests will require the user to be authenticated.</p>
</li>
</ul>
<p>Next, we set up our application to validate incoming tokens using <code>.oauth2ResourceServer().jwt();</code>. This ensures that only requests with a valid token can access our secured endpoints.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730875088355/b0502e8e-88e4-4aab-bf52-81360892ffbb.png" alt="Diagram depicting a sequence of interactions among five components: Client, Web Module, Security Filter, Service, and Repository. Arrows represent steps for token authentication and accessing a service, including requests, validations, data fetching, and responses, with outcomes for both valid and invalid tokens." class="image--center mx-auto" width="2012" height="1531" loading="lazy"></p>
<p>Now, let’s walk through the diagram. When a client sends a request to access a resource, the <strong>Security Filter</strong> first checks if the provided JWT token is valid. If the token is valid, the request proceeds to the <strong>Service Module</strong> to fetch or process the data. If not, access is denied right away, and the client receives an error response.</p>
<p>This flow ensures that only authenticated users can access sensitive resources, keeping our application secure.</p>
<h2 id="heading-10-deployment-with-docker-and-cicd">10. Deployment with Docker and CI/CD</h2>
<p>In this section, we'll containerize each module using <strong>Docker</strong> to make our application easier to deploy and run consistently across different environments. We’ll also set up a <strong>CI/CD pipeline</strong> using GitHub Actions (but you can use Jenkins too if you prefer). Automating this process ensures that any changes you push are automatically built, tested, and deployed.</p>
<h3 id="heading-step-1-containerizing-with-docker">Step 1: Containerizing with Docker</h3>
<p>We start by creating a <strong>Dockerfile</strong> for the <strong>Web Module:</strong></p>
<pre><code class="lang-java">FROM openjdk:<span class="hljs-number">11</span>-jre-slim
COPY target/web-<span class="hljs-number">1.0</span>-SNAPSHOT.jar app.jar
ENTRYPOINT [<span class="hljs-string">"java"</span>, <span class="hljs-string">"-jar"</span>, <span class="hljs-string">"/app.jar"</span>]
</code></pre>
<p>Here, we’re using a lightweight version of Java 11 to keep our image size small. We copy the compiled <code>.jar</code> file into the container and set it up to run when the container starts.</p>
<h3 id="heading-step-2-using-docker-compose-for-multi-module-deployment">Step 2: Using Docker Compose for Multi-Module Deployment</h3>
<p>Now, we'll use a <strong>Docker Compose</strong> file to orchestrate multiple modules together:</p>
<pre><code class="lang-java">version: <span class="hljs-string">'3'</span>
services:
  web:
    build: ./web
    ports:
      - <span class="hljs-string">"8080:8080"</span>
  service:
    build: ./service
    ports:
      - <span class="hljs-string">"8081:8081"</span>
</code></pre>
<p>With this setup, we can run both the <strong>Web Module</strong> and the <strong>Service Module</strong> at the same time, making it easy to spin up the entire application with a single command. Each service is built separately from its own directory, and we expose the necessary ports to access them.</p>
<h3 id="heading-cicd-example-with-github-actions">CI/CD Example with GitHub Actions</h3>
<pre><code class="lang-java">name: CI Pipeline

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout<span class="hljs-meta">@v2</span>
    - name: Set up JDK <span class="hljs-number">11</span>
      uses: actions/setup-java<span class="hljs-meta">@v2</span>
      with:
        java-version: <span class="hljs-string">'11'</span>
    - name: Build with Maven
      run: mvn clean install
</code></pre>
<p>This pipeline automatically kicks in whenever you push new code or create a pull request. It checks out your code, sets up Java, and runs a Maven build to ensure everything is working correctly.</p>
<h2 id="heading-11-best-practices-and-advanced-use-cases">11. Best Practices and Advanced Use Cases</h2>
<p>The following best practices ensure maintainability and scalability.</p>
<h3 id="heading-best-practices">Best Practices</h3>
<ul>
<li><p><strong>Avoid Circular Dependencies</strong>: Ensure modules don’t have circular references to avoid build issues.</p>
</li>
<li><p><strong>Separate Concerns Clearly</strong>: Each module should focus on one responsibility.</p>
</li>
<li><p><strong>Centralized Configurations</strong>: Manage configurations centrally for consistent setups.</p>
</li>
</ul>
<h3 id="heading-advanced-use-cases">Advanced Use Cases</h3>
<ol>
<li><p><strong>Asynchronous Messaging with Kafka</strong>: Use Kafka for decoupled communication between services. Modules can publish and subscribe to events asynchronously.</p>
</li>
<li><p><strong>REST Client with Feign</strong>: Use Feign to call services within modules. Define a Feign client interface for communication.</p>
</li>
<li><p><strong>Caching for Performance</strong>: Use Spring Cache in the service module for optimizing data retrieval.</p>
</li>
</ol>
<h2 id="heading-conclusion-and-key-takeaways">Conclusion and Key Takeaways</h2>
<p>A multi-module Spring Boot project provides modularity, scalability, and ease of maintenance.</p>
<p>In this tutorial, you learned to set up modules, manage inter-module communication, handle errors, add security, and deploy with Docker.</p>
<p>Following best practices and using advanced techniques like messaging and caching will further optimize your multi-module architecture for production use.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Rate Limiting? Exploring the Role of Rate Limiting in Protecting Web APIs from Attacks ]]>
                </title>
                <description>
                    <![CDATA[ Back-end servers are the powerhouse of modern-day applications; hence, a high level of expertise goes into building them. However, it's important to ensure that these back-end servers are well-secured from bad actors (hackers, phishers). These bad el... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-rate-limiting-web-apis/</link>
                <guid isPermaLink="false">66d884befdf6891c419f8901</guid>
                
                    <category>
                        <![CDATA[ #cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi ]]>
                </dc:creator>
                <pubDate>Wed, 04 Sep 2024 16:03:10 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725036062594/0efa7e12-c5d5-410f-ad9c-ec6a67a31f7c.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Back-end servers are the powerhouse of modern-day applications; hence, a high level of expertise goes into building them. However, it's important to ensure that these back-end servers are well-secured from bad actors (hackers, phishers).</p>
<p>These bad elements access the back-end servers through vulnerable points in the gateways to wreak havoc, stealing relevant info and negatively affecting application performance and efficiency via various forms of API attacks such as SQL and non-SQL-based injections, Distributed Denial-of-Service (DDoS) attacks, code malware, and other methods to exploit vulnerabilities.</p>
<p>In this article, I will be focusing on rate limiting, an important hack that helps protect the back-end API from being exploited by hackers via the use of DDoS, Brute-force attacks and other related malicious activities. But first of all, what does rate limiting mean?</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-rate-limiting">What is Rate Limitin</a><a class="post-section-overview" href="#heading-what-is-rate-limiting">g?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-importance-of-rate-limiting">Importance of Rate Limiting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-adoption-and-usage-of-rate-limiting-by-popular-sites">Adoption and Usage of Rate-Limiting by Popular Sites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-other-real-life-use-cases-of-api-rate-limiting">Other Real life Use-cases of API Rate Limiting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-does-rate-limiting-work">How Does Rate Limiting Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-examples-of-rate-limiting-algorithms">Examples of Rate Limiting Algorithms</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rate-limiting-best-practices">Rate Limiting Best Practices</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-what-is-rate-limiting">What is Rate Limiting?</h2>
<p>Rate limiting is a mechanism put in place to regulate the frequency of requests made by a client to the back-end server. It prevents the repetition of a client request within a defined time frame.</p>
<p>Why do we have to implement rate limiting in the API development? We'll discuss that in the next section.</p>
<h2 id="heading-importance-of-rate-limiting">Importance of Rate Limiting</h2>
<p>Here are some of the reasons why rate limiting is used in back-end application development.</p>
<h3 id="heading-ddos-attacks">DDoS Attacks</h3>
<p>First of all, it serves as a preventive measure to mitigate against DDoS attacks. DDoS attacks are malicious attacks on servers which involves flooding the server endpoints with multiple requests, often millions, resulting in reduced server efficiency and disruption of server functions. In most cases, they occur with the use of automated bots.</p>
<p>These attacks can be volumetric, protocol-based or application layer-based. A key example of this form of attack occurred on the GitHub website in the year 2018.</p>
<h3 id="heading-web-scraping">Web Scraping</h3>
<p>Rate limiting also plays a role in protecting web applications and web servers from unauthorized web scrapers and web crawlers. These tools, also automated, usually emit requests continually to collect relevant website data which can be exposed to unauthorized. Having a good rate limiter in place helps to prevent all these.</p>
<h3 id="heading-brute-force-attack">Brute Force Attack</h3>
<p>This involves trying to gain access to a server's resources by trying all possible configurations to get access to the resource. This could be done manually but is mostly automated with the use of bots as it is resource-consuming. Rate limiting also proves effective in preventing these form of attacks by disabling the requests if they exceed the required number of requests within a specific time frame.</p>
<h3 id="heading-resource-optimization">Resource Optimization</h3>
<p>Server requests usually cost the API owners some expenses in terms of running and maintenance cost. Having a rate limiter in place helps to regulate the number of requests the server can handle, help conserve cost and maximize efficiency. Subsequently, we will highlight some algorithms which rate limiters are built on.</p>
<h2 id="heading-adoption-and-usage-of-rate-limiting-by-popular-sites">Adoption and Usage of Rate-Limiting by Popular Sites</h2>
<p>Rate limiting as a security measure has been adopted by a lot of tech products, ranging from large-scale to small-scale applications. For example, Twitter (X) has a rale limit feature implemented in the application programming interfaces they provide to developers.</p>
<p>These interfaces allow access to Twitter sign-up extension and other features made available by Twitter. To guarantee the efficient running of these interfaces, Twitter imposed a rate limit of 50 tweet post requests per user every 24 hours. More details about this can be found <a target="_blank" href="https://developer.twitter.com/en/docs/twitter-api/rate-limits">here</a>.</p>
<h2 id="heading-other-real-life-use-cases-of-api-rate-limiting">Other Real life Use-cases of API Rate Limiting</h2>
<p>The use of an application programming interface isn't limited to just what popular sites like Twitter use it for. Here are some other real-life applications of rate-limiting in today's world.</p>
<h3 id="heading-reducing-the-incidence-of-spamming">Reducing the Incidence of Spamming</h3>
<p><a target="_blank" href="https://www.emailtooltester.com/en/blog/spam-statistics/#:~:text=Survey%20Methodology-,Key%20statistics,spam%20messages%20in%20some%20form.">Research</a> reveals that over 160 billion spam emails are sent daily. Hence this has prompted the implementation of rate-limiting to curb the spread of unsolicited messages and spam content via messaging and emailing platforms over a specific time range. By so doing, it encourages responsible use of these platforms.</p>
<h3 id="heading-tackling-fraudulent-activities">Tackling Fraudulent Activities</h3>
<p>Rate limiting is currently implemented across web applications to help detect unusual web application activities by some users which may possess fraudulent intents. This measure serves to prevent and mitigate the ongoing fraudulent transactions being performed over the application server.</p>
<h3 id="heading-disabling-malicious-user-authentication">Disabling Malicious User Authentication</h3>
<p>Individuals with malicious intent may want to compromise the web servers by taking several measures such as brute force, DDoS and other techniques to take over other users' accounts.</p>
<p>However, several sites have efficient rate limit systems in places which limit the amount of login attempts an individual has to a site within a specific time range. This also contributes to web security measures.</p>
<h2 id="heading-how-does-rate-limiting-work">How Does Rate Limiting Work?</h2>
<p>Rate-limiting tools used in applications are implemented based on different algorithm structures. These algorithms guide the functionality of the rate-limiting tool whose end goal is to limit the number of requests a server receives per time to enhance its efficiency.</p>
<h2 id="heading-examples-of-rate-limiting-algorithms">Examples of Rate Limiting Algorithms</h2>
<p>Here are some of the most popular algorithms currently in use.</p>
<h3 id="heading-fixed-window-algorithm">Fixed Window Algorithm</h3>
<p>This algorithm is based on fixing a static definite time interval by the server for all clients, regulating the number of requests that can be made to the server, irrespective of the number of clients accessing the API.</p>
<p>For example, setting a request limit of five minutes prevents any client from accessing the endpoint until the expiration of the five minutes window. This model isn’t cost-effective.</p>
<h3 id="heading-sliding-window-algorithm">Sliding Window Algorithm</h3>
<p>This algorithm is similar in configuration to the fixed window algorithm but it provides a solution to the fixed window algorithm by individualizing client access to a given number of requests within a specific time interval by creating independent time intervals for each client.</p>
<p>For example, if Client A accesses the request by 10:00, the client is allowed to make 10 requests until the expiration of the time by 10:03, while Client B who accesses the request by 10:02 is allowed to make 10 requests until the expiration by 10:05.</p>
<h3 id="heading-leaking-bucket-algorithm">Leaking Bucket Algorithm</h3>
<p>This algorithm is based on the literal meaning of its name: the leaking bucket. It ensures that only a specific number of requests can be processed by the server at any given time. Any requests exceeding this number will be discarded and issued an "<strong>error 429</strong>". This is to ensure that the server is not overloaded and to guarantee maintenance of server efficiency and speed.</p>
<h3 id="heading-token-bucket-algorithm">Token Bucket Algorithm</h3>
<p>This model is similar to the leaking bucket as there is a hypothetical bucket which serves as the rate limiter. This bucket serves to manage tokens and new tokens are added periodically into the bucket.</p>
<p>When a request is made, a token gets discarded, and this continues until all the tokens in the bucket get depleted. At that point, any request made will be discarded with an "<strong>error 429</strong>". This also helps to prevent server congestion and ensure maximal efficiency.</p>
<h2 id="heading-rate-limiting-best-practices">Rate Limiting Best Practices</h2>
<p>Efficient web API development is mainly achievable by following the best API development practices. To maximize the use of a rate limiter as an API security measure, the following needs to be implemented.</p>
<ul>
<li><p><strong>Firstly, choose a compatible rate-limiting algorithm.</strong> Having a strong rate-limiting algorithm in place will be essential to achieve the desired result. Choosing the best rate-limiting algorithm in sync with your API endpoint will also be needed.</p>
</li>
<li><p><strong>Ensure that the limit sets are within the reasonable limit ranges</strong>. Having arbitrary rate limit parameters set could negatively affect user experience and that could defeat its purpose. Setting a reasonable time limit to maximize user experience and militate against attacks has proven to be much more effective.</p>
</li>
<li><p><strong>Ensure efficient error handling and provide necessary feedback to the client.</strong> The default rate limiting error code is error code 429. Appropriate handling of the errors that occur during the API usage especially due to the abuse of the API will be necessary to provide the necessary feedback to the user.</p>
</li>
<li><p><strong>Implement flexible rate-limiting mechanisms across several parameters.</strong> Setting a fixed time interval across all endpoints seems to be a bad practice as some API endpoints are much more data-sensitive than others. Hence, having a flexible rate limiter that sets parameters in order of relevance helps to maximize server efficiency and ensure security.</p>
</li>
<li><p><strong>Ensure the provision of appropriate application logging, monitoring and observability tools.</strong> Having in place API metrics, logging, monitoring and observability tools also helps to serve as an additional security hack for Web APIs as they help monitor server activity, and through the use of monitoring alerts, notify the server developer when suspicious requests are detected on the server.</p>
</li>
<li><p><strong>Ensure synchronicity of rate limiting and other API security measures.</strong> Proper synchronicity of rate limiters with other API security hacks should be harnessed to potentiate the API security measures. Adequate knowledge of the security measures and expertise is needed in order not to counteract the existing security measures.</p>
</li>
<li><p><strong>Ensure proper API documentation.</strong> Adequate API documentation is also needed to ensure users, other developers and clients alike are aware of the rate-limiting practice in place to ensure compliance with the rate-limiting rules.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, we have highlighted rate limiting as an important API security hack and some of it's real life use cases.</p>
<p>Feel free to check out my other articles <a target="_blank" href="https://linktr.ee/tobilyn77">here</a>. Till next time, keep on coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Backend Development by Building Three Projects [Full Course] ]]>
                </title>
                <description>
                    <![CDATA[ To become a great backend developer, you need to build a lot of projects. We just posted a course on the freeCodeCamp.org YouTube channel that will help you improve your backend development skills by teaching you to build three full projects. Tomi To... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/backend-web-development-three-projects/</link>
                <guid isPermaLink="false">66b200af09c44225ad2c3961</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Thu, 11 Apr 2024 15:26:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/tomi.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>To become a great backend developer, you need to build a lot of projects. We just posted a course on the freeCodeCamp.org YouTube channel that will help you improve your backend development skills by teaching you to build three full projects.</p>
<p>Tomi Tokko developed this course. He's a popular teacher, and despite his young age has taught many courses over the past 4 years.</p>
<p>This course not only enhances your backend development skills but also gives you a taste of combining frontend technologies to create full-fledged applications.</p>
<p>Tomi offers an engaging and detailed course that guides you through building three projects.</p>
<p>Here are the projects you will build:</p>
<ol>
<li><strong>AI Blog Article Generator</strong>: Dive into the world of artificial intelligence as you create a tool that generates blog articles. You will learn about the integration of AI in web development.</li>
<li><strong>Netflix Clone</strong>: Build a clone of Netflix, where you'll implement user authentication, video streaming, and a dynamic, responsive user interface.</li>
<li><strong>Spotify Clone</strong>: Create a music streaming platform, learning how to manage audio files, user playlists, and real-time data streaming.</li>
</ol>
<p>And here are the technologies you will use:</p>
<ul>
<li><strong>Python</strong>: Known for its readability and efficiency, Python is a favorite among backend developers. You'll use Python to build robust backend logic and handle server-side operations.</li>
<li><strong>Django</strong>: This high-level Python web framework encourages rapid development and clean, pragmatic design. With Django, you'll structure your backend, manage databases, and ensure your applications are secure and scalable.</li>
<li><strong>JavaScript</strong>: While primarily known for frontend development, JavaScript's role in this course is to add interactivity and enhance the user experience of your applications.</li>
<li><strong>PostgreSQL</strong>: This powerful, open-source object-relational database system offers reliability, feature robustness, and performance. You'll use PostgreSQL to manage and query your application data efficiently.</li>
<li><strong>Tailwind CSS</strong>: A utility-first CSS framework, Tailwind CSS enables you to style your applications without leaving your HTML. It's a powerful tool for designing responsive and visually appealing user interfaces.</li>
</ul>
<p>Whether you're new to backend development or looking to expand your skill set, this course offers a structured and detailed path to mastering essential technologies and concepts. Watch the full course on <a target="_blank" href="https://youtu.be/ftKiHCDVwfA">the freeCodeCamp.org YouTube channel</a> (10-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/ftKiHCDVwfA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Back-End Development – Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Are you ready to dive into the world of Python back-end development? Whether you’re a beginner looking to learn the basics or an experienced developer wanting to upgrade your skills, this handbook is your ultimate guide. Imagine being able to build f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-back-end-development-the-beginners-guide/</link>
                <guid isPermaLink="false">66b99b0ebe5923657131acd8</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vahe Aslanyan ]]>
                </dc:creator>
                <pubDate>Thu, 08 Feb 2024 00:04:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Python-Backend-Development-Cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you ready to dive into the world of Python back-end development? Whether you’re a beginner looking to learn the basics or an experienced developer wanting to upgrade your skills, this handbook is your ultimate guide.</p>
<p>Imagine being able to build full-featured web applications, handle large-scale data analysis, and create robust architecture designs using Python. With its vast ecosystem of libraries and built-in support for machine learning, Python has become the go-to programming language for back-end development.</p>
<p>In this guide, we’ll explore everything you need to know about Python back-end development. We’ll discuss the role and responsibilities of a Python back-end developer, popular web frameworks, and the latest trends in the industry. We’ll also explore real-world applications and case studies, giving you practical insights into building efficient and scalable back-end systems.</p>
<p>Whether you’re interested in data-driven applications or API development, this tutorial will provide you with valuable knowledge and resources to excel in the world of Python back-end development. So, let’s get started.</p>
<h2 id="heading-table-of-contents">Table Of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-how-to-launch-your-career-as-a-python-back-end-developer">How to Launch Your Career as a Python Back-End Developer</a></li>
<li><a class="post-section-overview" href="#heading-what-is-python-back-end-development">What is Python Back-end Development?</a></li>
<li><a class="post-section-overview" href="#heading-python-back-end-developer-skills">Python Back-end Developer Skills</a></li>
<li><a class="post-section-overview" href="#heading-python-back-end-career-paths">Python Back-end Career Paths</a></li>
<li><a class="post-section-overview" href="#heading-recommended-python-libraries-for-backend-development">Recommended Python Libraries for Back-end Development</a></li>
<li><a class="post-section-overview" href="#heading-how-to-become-a-python-back-end-developer">How to Become a Python Back-end Developer</a></li>
<li><a class="post-section-overview" href="#heading-database-management-in-python">Database Management in Python</a></li>
<li><a class="post-section-overview" href="#heading-security-and-authentication-in-back-end-development">Security and Authentication in Back-end Development</a></li>
<li><a class="post-section-overview" href="#heading-how-to-prepare-for-a-back-end-python-developer-job">How to Prepare for a Back-end Python Developer Job</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-how-to-launch-your-career-as-a-python-back-end-developer">How to Launch Your Career as a Python Back-End Developer</h2>
<p>Are you ready to embark on an exciting journey as a Python back-end developer? Python's incredible versatility and power have made it a standout choice in the tech industry, especially for back-end development. This guide is your first step toward a flourishing career in this field.</p>
<p>Here are some of the topics we'll cover in this handbook:</p>
<h3 id="heading-pythons-critical-role-in-back-end-development">Python's Critical Role in Back-End Development</h3>
<p>Python, often thought of as a front-end language, is actually a powerhouse in back-end development. Its clear syntax, robust support, and expansive library ecosystem are pivotal in crafting efficient, scalable web applications. </p>
<p>So try to dispel any myths about Python's performance limitations – advancements in interpreter technology and optimized libraries mean Python adeptly manages large code bases and numerous concurrent connections.</p>
<h3 id="heading-career-pathways-in-python-back-end-development">Career Pathways in Python Back-End Development</h3>
<p>As a Python back-end developer, numerous career avenues await you. From junior developers to system architects, Python opens doors to diverse roles. Your expertise in Python can lead you to high-demand sectors, where your skills in data analysis, machine learning, and API development are highly valued.</p>
<h3 id="heading-industry-demand-and-career-growth">Industry Demand and Career Growth</h3>
<p>The demand for skilled Python back-end developers is soaring. Businesses across various industries seek professionals who can navigate Python's capabilities to solve complex challenges. By learning Python, you position yourself at the forefront of an ever-growing job market.</p>
<h3 id="heading-community-involvement-and-networking">Community Involvement and Networking</h3>
<p>Engage with the Python community. Participate in forums, contribute to open-source projects, and network with fellow developers. This involvement is not just about learning – it's about building relationships that can propel your career forward.</p>
<h3 id="heading-structured-learning-for-success">Structured Learning for Success</h3>
<p>Begin your Python journey with a structured learning plan. Start with the basics – Python's syntax and features – and utilize the wealth of online tutorials and resources available. </p>
<p>Then you can progress to exploring web frameworks like Django, Flask, and FastAPI. Each framework has its unique strengths and will equip you with the skills to build complex web applications.</p>
<h3 id="heading-build-a-personal-portfolio">Build a Personal Portfolio</h3>
<p>Create a portfolio that showcases your Python projects, from simple to complex. These projects are proof of your skills and will serve as a cornerstone for your professional growth. They are not just demonstrations of your ability, but valuable learning experiences.</p>
<h3 id="heading-seek-mentorship-and-continuous-learning">Seek Mentorship and Continuous Learning</h3>
<p>Remember, becoming proficient in Python back-end development is a journey of continuous learning and practice. Seek mentorship from experienced developers and remain curious and motivated. Your path to becoming a Python back-end developer is filled with endless possibilities and opportunities for growth.</p>
<p>Embrace this journey with enthusiasm and determination, and watch as doors open in the dynamic world of Python back-end development.</p>
<h2 id="heading-what-is-python-back-end-development">What is Python Back-end Development?</h2>
<p>Python allows you to create innovative backend solutions. This versatile language is swiftly becoming a go-to for developers seeking to create powerful server-side components for web applications. </p>
<p>But its simplicity and versatility are just the beginning. Python enables you to design solutions that make real-world impacts, bringing efficiency and innovation to various industries.</p>
<h3 id="heading-the-expansive-role-of-python-in-crafting-web-applications">The Expansive Role of Python in Crafting Web Applications</h3>
<p>When you write server-side code using Python, you're directly handling requests from the front-end and engaging with databases and other resources. </p>
<p>The beauty of Python lies in its support for frameworks like Django, Flask, and FastAPI, simplifying the development of complex web applications. This is where you transform your code into functional, user-centric web applications.</p>
<h3 id="heading-how-to-harness-pythons-advantages-for-career-advancement">How to Harness Python's Advantages for Career Advancement</h3>
<p>Python is renowned for its readability and clean syntax, making it an ideal language for both beginners and experienced developers. Its extensive library ecosystem equips you with tools to expedite development processes. </p>
<p>But there's more – Python's prowess in machine learning and data analysis opens up avenues in sophisticated back-end operations. This versatility allows for seamless integration with various databases, both SQL and NoSQL, catering to a wide array of applications. </p>
<p>As a career coach, I recommend leveraging these advantages by exploring real-world applications and community projects. This practical exposure not only enhances your skill set but also showcases your capabilities to potential employers.</p>
<h3 id="heading-how-to-tackle-pythons-misconceptions-with-confidence">How to Tackle Python's Misconceptions with Confidence</h3>
<p>Python, like any language, has its debates. Concerns about its performance, particularly in comparison to statically typed languages, do arise. </p>
<p>But Python's dynamic nature and interpreted execution, when harnessed with efficient libraries and optimization techniques, are more than capable of powering large-scale web applications. Its multi-threading and asynchronous features allow handling numerous concurrent connections, a vital aspect of modern web development. </p>
<p>You can enhance your expertise in these areas through specialized training and community workshops, focusing on Python’s advanced features and performance optimization.</p>
<h3 id="heading-stay-focused-and-curious">Stay Focused and Curious</h3>
<p>As you embark on this journey, remember that Python back-end development is a continuous learning curve. Stay updated with the latest trends and advancements in Python. Engage in lifelong learning, explore new challenges, and actively seek opportunities for growth. </p>
<p>Building a strong foundation in Python, coupled with an eagerness to adapt and innovate, will set you apart in this dynamic field.</p>
<p>So as you can see, Python back-end development is not just about coding – it's about creating, innovating, and constantly evolving. By embracing the versatility and power of Python and staying committed to continuous learning and skill enhancement, you are opening doors to a thriving career in technology.</p>
<h2 id="heading-python-back-end-developer-skills">Python Back-End Developer Skills</h2>
<p>Aspiring Python back-end developers need to acquire a specific set of skills and competencies to excel in their roles. These skills encompass a combination of programming knowledge, familiarity with web frameworks, database management, and an understanding of security and authentication protocols.</p>
<h3 id="heading-proficiency-in-python-programming">Proficiency in Python Programming</h3>
<p>Being proficient in Python is an essential skill for any Python back-end developer. A deep understanding of the language’s syntax, features, and best practices allows developers to write efficient and reliable code. </p>
<p>Python’s simplicity, readability, and vast ecosystem of libraries make it a popular choice for back-end development.</p>
<p>If you want to get started learning Python, freeCodeCamp has a couple certifications just for you. Check out <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/">Scientific Computing with Python here</a>, and <a target="_blank" href="https://www.freecodecamp.org/learn/data-analysis-with-python/">Data Analysis with Python here</a>. </p>
<p>There are also a number of great beginner-friendly Python courses on the freeCodeCamp YouTube channel – like <a target="_blank" href="https://www.freecodecamp.org/news/learn-python-from-harvard-university/">this one from Harvard</a>.</p>
<p>And if you want some great Python coding examples, check out these handbooks <a target="_blank" href="https://www.freecodecamp.org/news/python-code-examples-simple-python-program-example/">here</a> and <a target="_blank" href="https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/">here</a>.</p>
<h3 id="heading-learn-python-web-frameworks">Learn Python Web Frameworks</h3>
<p>Python offers several powerful web frameworks that simplify the development process and provide built-in support for building full-featured web applications. </p>
<p>Popular frameworks like Django, Flask, and FastAPI offer different approaches to web development, allowing developers to choose the one that best suits their project’s requirements.</p>
<p>You can learn all about Django from the famous Dr. Chuck <a target="_blank" href="https://www.freecodecamp.org/news/django-for-everybody-learn-the-popular-python-framework-from-dr-chuck/">in this course</a> on freeCodeCamp's YouTube channel.</p>
<p>And you can learn about Flask by building an e-commerce app <a target="_blank" href="https://www.freecodecamp.org/news/learn-the-flask-python-web-framework-by-building-a-market-platform/">in this course</a>.</p>
<p>And <a target="_blank" href="https://www.freecodecamp.org/news/fastapi-quickstart/">this handbook</a> will teach you FastAPI basics while <a target="_blank" href="https://www.freecodecamp.org/news/fastapi-helps-you-develop-apis-quickly/">this course</a> will solidify your knowledge.</p>
<h3 id="heading-learn-database-management">Learn Database Management</h3>
<p>Python back-end developers must have a good grasp of database management, including both SQL (Structured Query Language) and NoSQL (Non-relational) databases. </p>
<p>Understanding how to design database schemas, write efficient queries, and ensure data integrity is crucial for building robust back-end systems.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-full-course/">Here's a course</a> that'll teach you SQL basics for data storage and retrieval.</p>
<p>And <a target="_blank" href="https://www.freecodecamp.org/news/how-to-read-and-write-data-to-a-sql-database-using-python/">here's a quick tutorial</a> that teaches you how to use Python to read data from and write data to a table in SQL databases.</p>
<p>For NoSQL databases, <a target="_blank" href="https://www.freecodecamp.org/news/learn-nosql-in-3-hours/">here's a full course</a> that teaches you all about how they work.</p>
<h3 id="heading-learn-security-and-authentication">Learn Security and Authentication</h3>
<p>As back-end developers handle sensitive user data and interact with external systems, they must possess knowledge of security and authentication protocols. This includes understanding concepts like encryption, secure communication, user authentication, and authorization. Familiarity with frameworks and libraries that provide security features is also essential.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-a-secure-django-web-app/">Here's a helpful tutorial</a> on web security in Django, and <a target="_blank" href="https://www.freecodecamp.org/news/how-to-setup-user-authentication-in-flask/">here's a tutorial</a> about setting up authentication in a Flask app. Hopefully these will give you some basic ideas and inspire you to learn more if you need to do so.</p>
<p>Developers who possess these skills will be well-equipped to tackle the challenges of back-end development using Python. </p>
<p>By continuously honing their skills and staying updated with the latest trends and best practices, Python back-end developers can deliver high-quality and secure web applications.</p>
<h2 id="heading-python-back-end-career-paths">Python Back-End Career Paths</h2>
<p>As a Python back-end developer, you have a wide range of career paths to choose from. The demand for skilled Python developers is on the rise, and there are numerous opportunities in various fields. </p>
<p>Here are some of the career paths you can explore:</p>
<h3 id="heading-web-development">Web Development</h3>
<p>Web development is one of the most common career paths for Python back-end developers. You can work on building and maintaining websites, web applications, and content management systems. </p>
<p>With Python’s versatility and the availability of web frameworks like Django and Flask, you can create robust and scalable web solutions.</p>
<h3 id="heading-data-analysis">Data Analysis</h3>
<p>Python is widely used for data analysis and manipulation. As a Python back-end developer, you can work with large datasets, perform statistical analysis, and create data visualizations. Tools like NumPy, Pandas, and Matplotlib are commonly used in this field.</p>
<h3 id="heading-machine-learning">Machine Learning</h3>
<p>Python is the language of choice for machine learning and artificial intelligence. As a Python back-end developer, you can develop machine learning models, implement deep learning algorithms, and work on natural language processing projects. Libraries like TensorFlow and scikit-learn are popular for this purpose.</p>
<h3 id="heading-devops-and-deployment">DevOps and Deployment</h3>
<p>Python is also valuable in the DevOps field. You can work on automating deployment processes, managing infrastructure, and building scalable systems. With tools like Docker and Kubernetes, you can streamline the deployment and maintenance of applications.</p>
<h3 id="heading-backend-architecture-and-design">Backend Architecture and Design</h3>
<p>If you have a strong grasp of backend architecture and design principles, you can pursue a career as a backend architect or technical lead. You will be responsible for designing scalable, efficient, and secure backend systems and ensuring smooth integration with frontend components.</p>
<p>The salaries for Python back-end developers vary based on experience, location, and industry. But the <a target="_blank" href="https://builtin.com/salaries/dev-engineer/python-developer">average salary for Python professionals is quite competitive</a>, with ample room for growth and advancement.</p>
<p>Remember, this is just a glimpse of the career paths available to Python back-end developers. With the continuous growth and evolution of technology, new opportunities are constantly emerging. Stay updated with the latest trends and technologies to make the most out of your career in Python back-end development.</p>
<h2 id="heading-recommended-python-libraries-for-backend-development">Recommended Python Libraries for Backend Development</h2>
<p>When it comes to Python backend development, leveraging the right libraries can significantly streamline the development process and enhance the functionality of your web applications. </p>
<p>Here are five Python tools that can simplify and optimize your backend development workflow:</p>
<h3 id="heading-flask">Flask</h3>
<p><a target="_blank" href="https://flask.palletsprojects.com/en/3.0.x/">Flask</a> is a micro web framework that offers simplicity and ease of use without sacrificing functionality. It provides a minimalistic syntax and focuses on the core features of web development, making it an excellent choice for small to medium-sized projects. </p>
<p>Flask’s modular design allows developers to add the necessary extensions to create a full-featured web application. It is highly extensible and beginner-friendly, making it a great library for developers getting started with Python backend development.</p>
<h3 id="heading-fastapi">FastAPI</h3>
<p>FastAPI is relatively new, but it's rapidly gaining popularity as a high-performance web framework. It combines modern, asynchronous programming techniques with the simplicity and productivity of the Python language. </p>
<p>FastAPI leverages the power of type hints and automatic documentation generation, making it easier for developers to build robust and well-documented APIs. Its speed and efficiency make it an excellent choice for building scalable backend systems.</p>
<h3 id="heading-django">Django</h3>
<p><a target="_blank" href="https://www.djangoproject.com/">Django</a> is a widely used, batteries-included web framework that simplifies the process of building complex web applications. It provides built-in support for various functionalities, including authentication, database management, and URL routing. </p>
<p>Django’s robustness and scalability have made it a preferred choice for a wide range of applications, from basic websites to large-scale enterprise systems.</p>
<h3 id="heading-tornado">Tornado</h3>
<p><a target="_blank" href="https://github.com/tornadoweb/tornado">Tornado</a> is a popular open-source web framework that excels in handling high-performance, real-time web applications. Its non-blocking architecture makes it ideal for building scalable applications that require handling a large number of concurrent connections. </p>
<p>Tornado’s lightweight and efficient design, along with its support for long polling and websockets, makes it a valuable tool for developers working on real-time applications.</p>
<h3 id="heading-pyramid">Pyramid</h3>
<p><a target="_blank" href="https://trypyramid.com/">Pyramid</a> is a powerful and flexible web framework that prioritizes simplicity and speed. It provides a solid foundation for building both small and large-scale web applications. </p>
<p>Pyramid follows the principle of “pay only for what you need,” allowing developers to choose and integrate various components according to their requirements. </p>
<p>With its extensive documentation and active community, Pyramid is a popular choice among Python developers.</p>
<p>By utilizing these libraries in your Python backend development projects, you can benefit from their extensive features and community support. Each library has its own strengths, so it’s essential to evaluate your specific project requirements and choose the one that best fits your needs.</p>
<h2 id="heading-how-to-become-a-python-back-end-developer">How to Become a Python Back-End Developer</h2>
<p>Becoming a Python back-end developer requires a combination of technical skills, practical experience, and continuous learning. Here are some actionable steps and guidance to help you kickstart your journey:</p>
<h3 id="heading-fortify-your-python-foundations">Fortify Your Python Foundations</h3>
<p>Embarking on your Python back-end development journey begins with a deep dive into Python’s fundamentals. Set specific, measurable goals to master Python’s syntax and core concepts. </p>
<p>For instance, aim to understand basic syntax within the first couple weeks, or complete a mini-project using object-oriented principles within a month.</p>
<p>Supplement your learning with practical exercises at the end of each session. These exercises reinforce theoretical knowledge and aid in retention. </p>
<p>It's also a good idea to engage in peer review and collaboration by joining coding forums or local Python groups. This exposure can offer new perspectives and enhance your problem-solving skills, forming a solid foundation for your journey.</p>
<h3 id="heading-expand-your-web-development-horizons">Expand Your Web Development Horizons</h3>
<p>As you progress, broaden your understanding of web development essentials. While your focus may be on back-end development, a well-rounded knowledge of front-end technologies like HTML, CSS, and JavaScript is crucial. </p>
<p>Explore resources or short courses that offer a comprehensive overview of these front-end technologies. You can also analyze real-world applications to see how these technologies are applied in practice. </p>
<p>This approach provides a holistic view of web development, preparing you to create more integrated and efficient back-end systems.</p>
<h3 id="heading-learn-python-web-frameworks-1">Learn Python Web Frameworks</h3>
<p>Venture further into Python’s powerful web frameworks, such as Django, Flask, and FastAPI that we discussed above. Each framework has its unique strengths, so consider undertaking a comparative project where you utilize different frameworks for the same application. </p>
<p>This practical experience will deepen your understanding of each framework’s capabilities. </p>
<p>Engage actively in community forums, workshops, and contribute to open-source projects related to these frameworks. Such community engagement is not only enriching but also keeps you abreast of the latest developments and best practices in Python web frameworks.</p>
<h3 id="heading-learn-database-management-1">Learn Database Management</h3>
<p>Database management is a critical aspect of back-end development. Familiarize yourself with both SQL and NoSQL databases – we'll discuss these in more detail in subsequent chapters. </p>
<p>Hands-on projects involving the setup and management of databases will provide invaluable experience. Incorporate case studies of real-world database management scenarios to understand the challenges and best practices in this field. This knowledge is crucial for storing, retrieving, and manipulating data efficiently in your applications.</p>
<h3 id="heading-create-a-personal-portfolio">Create a Personal Portfolio</h3>
<p>Building a personal portfolio is essential in showcasing your skills. Select projects that not only demonstrate your technical prowess but also align with your career aspirations. </p>
<p>For instance, if data science intrigues you, focus on projects that involve data analysis and manipulation. Regular portfolio reviews by mentors or peers can provide constructive feedback, helping you refine your portfolio to better reflect your capabilities and aspirations.</p>
<h3 id="heading-go-through-certifications-and-courses">Go Through Certifications and Courses</h3>
<p>Enhance your skills and professional standing by enrolling in relevant courses and obtaining certifications. Choose educational paths that align with your career goals, ensuring that your learning journey strategically builds towards your desired role. Customize your learning path to fit your personal learning style and pace, making your educational experience more effective and enjoyable.</p>
<h3 id="heading-keep-pace-with-industry-trends">Keep Pace with Industry Trends</h3>
<p>Stay updated with the latest trends in Python back-end development. Seek mentorship from industry professionals who can provide insights into current industry trends and offer valuable career advice. Regularly subscribe to industry newsletters, listen to podcasts, and follow influencers in the Python development space to stay informed.</p>
<p>Your path to becoming a skilled Python back-end developer involves a combination of solid foundational learning, practical application, continuous education, and active community engagement. Each step should be approached with dedication and enthusiasm, keeping you inspired and informed as you explore the vast possibilities of Python and back-end development.</p>
<p>Now let's get into some of the more nitty-gritty details of what it takes to work with Python on the back end.</p>
<h2 id="heading-database-management-in-python">Database Management in Python</h2>
<p>Database management is a crucial aspect of building robust and efficient applications in Python. It involves effectively organizing and manipulating data to support various operations. </p>
<p>In this chapter, we will explore the definition and significance of database management and provide an overview of SQL and NoSQL databases in Python.</p>
<p>Database management refers to the process of organizing, storing, and retrieving data in a structured manner. It plays a vital role in ensuring data integrity, enabling efficient data access, and facilitating data analysis. </p>
<p>By effectively managing databases, developers can create scalable and reliable systems that support various business needs.</p>
<h3 id="heading-sql-vs-nosql-making-the-informed-choice">SQL vs. NoSQL: Making the Informed Choice</h3>
<p>In the realm of databases, understanding the distinction between SQL and NoSQL is crucial. </p>
<p>SQL databases shine with their structured query language, offering unparalleled precision for applications that rely on complex queries and transactional integrity. They are the bedrock for scenarios demanding strict data consistency, detailed relationships, and clear schema definitions.</p>
<p>On the other hand, NoSQL databases bring flexibility to the table, catering to applications that deal with large volumes of unstructured data or need to scale rapidly. Their schema-less nature allows for quick adaptations and supports a variety of data models, including key-value, document, wide-column, and graph formats.</p>
<p>The decision between SQL and NoSQL hinges on the specific needs of your project. If your application requires meticulous data organization and complex transactions, SQL is the dependable choice. For projects that must scale dynamically or handle a diverse set of data structures, NoSQL offers the agility and scalability needed.</p>
<p>Choose wisely, focusing on the demands of your application and the data it will handle. Both SQL and NoSQL databases have their place in the technology landscape, each bringing strengths that, when matched with the right project requirements, can significantly enhance your application's performance and scalability.</p>
<h3 id="heading-sql-databases-in-python">SQL Databases in Python</h3>
<p>SQL databases play a crucial role in storing and managing data in Python applications. They provide a structured approach to data storage, utilizing tables with predefined schemas. </p>
<p>With SQL databases, you can efficiently organize and retrieve data, making them ideal for applications that require complex querying and relationships between data entities.</p>
<p>Let's look at an example.</p>
<p>When working with SQL databases in Python, you can use libraries like <code>sqlite3</code> and <code>SQLAlchemy</code> to connect to the database and perform operations. </p>
<p>For instance, you can establish a connection to an SQLite database using <code>sqlite3.connect()</code> and then execute SQL queries to retrieve and manipulate data. </p>
<p>Here, we're creating a table called <code>users</code> to store user information:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Connect to the database</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)

<span class="hljs-comment"># Create a cursor object</span>
cursor = conn.cursor()

<span class="hljs-comment"># Execute SQL queries</span>
cursor.execute(<span class="hljs-string">"SELECT * FROM users"</span>)
users = cursor.fetchall()

<span class="hljs-comment"># Print the results</span>
<span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users:
    print(user)

<span class="hljs-comment"># Close the connection</span>
conn.close()
</code></pre>
<h4 id="heading-connecting-to-sql-databases-using-python-libraries-like-sqlite3-and-sqlalchemy">Connecting to SQL databases using Python libraries like <code>sqlite3</code> and <code>SQLAlchemy</code></h4>
<p>To connect to SQL databases in Python, you can leverage libraries such as <code>sqlite3</code> and <code>SQLAlchemy</code>. These libraries provide convenient APIs to establish connections, execute queries, and handle database operations.</p>
<h4 id="heading-designing-database-schemas-for-sql-databases">Designing database schemas for SQL databases</h4>
<p>Designing an effective database schema is crucial for SQL databases. A well-designed schema ensures efficient data organization, optimal querying performance, and data integrity. When designing a schema, consider the relationships between different entities and define appropriate tables, columns, and constraints.</p>
<h4 id="heading-writing-efficient-sql-queries-and-ensure-data-integrity">Writing efficient SQL queries and ensure data integrity</h4>
<p>To maximize performance and ensure data integrity, it is important to write efficient SQL queries. Consider using indexes, optimizing joins, and using appropriate SQL clauses to retrieve the required data. You can also enforce data integrity by defining constraints, such as primary key and foreign key constraints.</p>
<p>By understanding SQL databases, connecting to them using libraries like <code>sqlite3</code> and <code>SQLAlchemy</code>, designing effective schemas, and writing efficient queries, you can effectively manage data storage in your Python applications.</p>
<h3 id="heading-nosql-databases-in-python">NoSQL Databases in Python</h3>
<p>NoSQL databases provide a flexible and scalable approach to data storage, making them suitable for various use cases in Python. </p>
<p>One popular NoSQL database is MongoDB, which allows for storing data in a document format. This makes it ideal for scenarios where data structures may evolve or have varying attributes.</p>
<p>For example, let's say you are working on a Python project that involves analyzing social media data. By using MongoDB and its document-oriented model, you can easily store and retrieve data such as user profiles, posts, and comments, without the need for a predefined schema. This flexibility allows for efficient handling of dynamic data.</p>
<p>Let's look at an example. We can use the <code>pymongo</code> library to connect and interact with the database. Here's an example of inserting a document into a collection called <code>products</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pymongo <span class="hljs-keyword">import</span> MongoClient

<span class="hljs-comment"># Connect to the MongoDB database</span>
client = MongoClient(<span class="hljs-string">'mongodb://localhost:27017/'</span>)

<span class="hljs-comment"># Access the database</span>
db = client[<span class="hljs-string">'social_media'</span>]

<span class="hljs-comment"># Access the collection for user profiles</span>
profiles_collection = db[<span class="hljs-string">'profiles'</span>]

<span class="hljs-comment"># Insert a new user profile document</span>
profile = {
    <span class="hljs-string">'username'</span>: <span class="hljs-string">'john_doe'</span>,
    <span class="hljs-string">'name'</span>: <span class="hljs-string">'John Doe'</span>,
    <span class="hljs-string">'followers'</span>: <span class="hljs-number">1000</span>
}
profiles_collection.insert_one(profile)

<span class="hljs-comment"># Retrieve all user profiles</span>
profiles = profiles_collection.find()

<span class="hljs-comment"># Print the user profiles</span>
<span class="hljs-keyword">for</span> profile <span class="hljs-keyword">in</span> profiles:
    print(profile)

<span class="hljs-comment"># Close the connection</span>
client.close()
</code></pre>
<h3 id="heading-how-do-nosql-databases-work">How Do NoSQL Databases Work?</h3>
<p>NoSQL databases represent a broad class of database management systems that differ significantly from traditional relational database systems (RDBMS). These databases are designed to excel in areas where relational databases might struggle, particularly in handling large volumes of unstructured or semi-structured data, accommodating rapid scaling, and facilitating agile development practices that require schema flexibility.</p>
<p>Unlike SQL databases that store data in tables with predefined schemas, NoSQL databases use a variety of data models, including key-value pairs, documents, wide-column stores, and graphs. This diversity allows them to store and manage data in a format that is closer to the data's native structure, enhancing the efficiency of data retrieval and manipulation.</p>
<p> As a result, NoSQL databases have become a popular choice for developing modern applications in web, mobile, and IoT domains, where the ability to handle vast amounts of varied data types and structures quickly is paramount.</p>
<p>One of the key strengths of NoSQL databases is their scalability. They are designed to scale out by distributing data across multiple servers, often in a distributed system environment. This contrasts with the scale-up approach of traditional RDBMS, where a single server's resources are increased. </p>
<p>NoSQL's distributed architecture enables horizontal scalability, improving performance and availability while managing the cost implications of dealing with big data.</p>
<p>Furthermore, NoSQL databases often provide flexible schemas, allowing developers to alter the data structure as the application evolves without needing to predefine the schema. This flexibility facilitates rapid development and iteration, making NoSQL databases particularly suited to projects with evolving data models or projects that must go to market quickly.</p>
<h4 id="heading-connecting-to-nosql-databases-with-python-libraries">Connecting to NoSQL Databases with Python Libraries</h4>
<p>Diving into NoSQL databases with Python opens a world of possibilities for handling diverse data types and structures. Python offers a variety of libraries tailored to different NoSQL databases, such as pymongo for MongoDB, redis-py for Redis, and cassandra-driver for Cassandra. Each library simplifies the connection process, enabling developers to interact with the database using Pythonic conventions. </p>
<p>Establishing a connection typically involves specifying the database URI and credentials, after which you can perform CRUD operations seamlessly. This step is crucial for leveraging the full potential of NoSQL databases in your Python applications, providing the flexibility to work with data as your project requires.</p>
<h4 id="heading-designing-data-models-for-nosql-databases">Designing Data Models for NoSQL Databases</h4>
<p>When it comes to NoSQL databases, designing effective data models is a game-changer. Unlike SQL databases that follow a strict schema, NoSQL databases allow for a more flexible data structure, which can be optimized based on the specific use case. </p>
<p>Whether you’re working with document, key-value, wide-column, or graph databases, understanding the strengths and use cases of each type enables you to design data models that enhance performance and scalability. </p>
<p>This involves considering how data is accessed and manipulated, ensuring that the model supports efficient querying and updates. Effective data modeling in NoSQL databases paves the way for building dynamic applications that can adapt to changing requirements.</p>
<h4 id="heading-writing-effective-queries-in-nosql-databases">Writing Effective Queries in NoSQL Databases</h4>
<p>To tap into the power of NoSQL databases, writing effective queries is key. Each type of NoSQL database offers unique querying capabilities, from MongoDB’s BSON-based syntax to the graph traversal languages of graph databases. Mastering these query languages allows developers to retrieve, update, and manipulate data efficiently.</p>
<p> The goal is to optimize query performance without compromising the flexibility and scalability that NoSQL databases provide. This requires a deep understanding of the database’s indexing capabilities and query execution plan, enabling developers to write queries that are both powerful and efficient.</p>
<h4 id="heading-ensuring-data-integrity-in-nosql-databases">Ensuring Data Integrity in NoSQL Databases</h4>
<p>Maintaining data integrity in NoSQL databases presents unique challenges, given their schema-less nature and eventual consistency model. But strategies such as implementing application-level validation, using database features for atomic operations, and understanding the database’s consistency guarantees can mitigate these challenges. </p>
<p>It’s also important to consider transaction support, where needed, to ensure that data remains consistent across operations. By carefully planning for data integrity, you can build NoSQL-backed applications that are not only scalable and flexible but also reliable, meeting the demands of modern web and mobile applications.</p>
<h4 id="heading-how-to-design-database-schemas-for-nosql-databases-and-their-types-document-key-value-and-so-on">How to design database schemas for NoSQL databases and their types (Document, Key-Value, and so on)</h4>
<p>When designing a database schema for a NoSQL database, it is crucial to consider the specific type of NoSQL database you are working with. For example, if you are using a document-oriented database like MongoDB, you can structure your data as JSON-like documents.</p>
<p>Let's say you are developing a Python application for an e-commerce platform. With a document-oriented NoSQL database, you can design your schema to represent products as documents, including attributes like name, price, and category. This schema flexibility allows for easy expansion and modification of data structures as your application evolves.</p>
<h4 id="heading-how-to-perform-crud-operations-with-nosql-databases-in-python">How to perform CRUD operations with NoSQL databases in Python</h4>
<p>CRUD operations (Create, Read, Update, Delete) are fundamental tasks when working with databases. In Python, you can perform these operations with NoSQL databases using libraries like <code>pymongo</code>.</p>
<p>For example, imagine you are building a sentiment analysis application in Python, and you are using a NoSQL database to store user reviews. With <code>pymongo</code>, you can easily create a new document to store a user's review, retrieve reviews based on specific criteria, update review ratings, or delete unwanted reviews. This flexibility in performing CRUD operations allows you to effectively manage and manipulate data in your NoSQL database.</p>
<h3 id="heading-database-schema-design">Database Schema Design</h3>
<p>A well-designed database schema is of utmost importance in Python frontend and backend development, NLP, data science, and machine learning. It provides the foundation for efficient data organization and retrieval. </p>
<p>Let's explore techniques for creating effective database schemas and tools for visualizing and documenting them.</p>
<p>When designing a database schema, consider the specific requirements of your application. </p>
<p>Start by identifying the entities and relationships that need to be represented. For example, in an e-commerce application, you may have entities such as customers, products, and orders. Each entity can be represented as a table with columns representing specific attributes.</p>
<p>Next, define the relationships between the entities using foreign keys. For instance, an order can be associated with a customer and contain multiple products. By defining these relationships, you ensure data consistency and enable efficient querying.</p>
<p>To create a well-designed database schema, it is essential to follow best practices such as normalizing the data. This involves breaking down data into smaller, logical units to minimize redundancy and improve data integrity. </p>
<p>For example, instead of storing customer addresses directly in the orders table, you can create a separate table for addresses and link them using foreign keys.</p>
<p>You should also consider the performance implications of your schema design. Indexing key columns can significantly improve query performance by allowing the database to quickly locate specific data. Be mindful of the trade-off between the number of indexes and the overhead they introduce during data modification operations.</p>
<p>When it comes to visualizing and documenting the database schema, there are various tools available. One popular tool is MySQL Workbench, which provides a graphical interface for designing and visualizing database schemas. Another useful tool is Lucidchart, which allows you to create professional-looking entity-relationship diagrams.</p>
<p>Here's an example of using the MySQL Workbench tool to design a database schema:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-69.png" alt="Image" width="600" height="400" loading="lazy">
<em>Screenshot of MySQL Workbench</em></p>
<p>Let's illustrate these concepts with an example. Suppose we are building a blog application, and we need to design the database schema. </p>
<p>We can start by identifying the entities: authors, posts, and comments. The authors table can have columns like id, name, and email. The posts table can have columns like id, title, content, and author_id (a foreign key referencing the authors table). The comments table can have columns like id, content, post_id (a foreign key referencing the posts table), and author_id (a foreign key referencing the authors table).</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Connect to the database</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)

<span class="hljs-comment"># Create a cursor object</span>
cursor = conn.cursor()

<span class="hljs-comment"># Create the tables</span>
cursor.execute(<span class="hljs-string">'''CREATE TABLE authors
                  (id INTEGER PRIMARY KEY, name TEXT, email TEXT)'''</span>)

cursor.execute(<span class="hljs-string">'''CREATE TABLE posts
                  (id INTEGER PRIMARY KEY, title TEXT, content TEXT, author_id INTEGER,
                  FOREIGN KEY(author_id) REFERENCES authors(id))'''</span>)

cursor.execute(<span class="hljs-string">'''CREATE TABLE comments
                  (id INTEGER PRIMARY KEY, content TEXT, post_id INTEGER, author_id INTEGER,
                  FOREIGN KEY(post_id) REFERENCES posts(id),
                  FOREIGN KEY(author_id) REFERENCES authors(id))'''</span>)

<span class="hljs-comment"># Close the connection</span>
conn.close()
</code></pre>
<p>By following these techniques and utilizing appropriate tools, you can create a well-designed database schema that supports efficient data management and retrieval in Python applications. Remember to constantly evaluate and refine your schema as your application evolves and new requirements arise.</p>
<h3 id="heading-query-optimization-and-performance">Query Optimization and Performance</h3>
<p>Optimizing SQL queries for better performance is essential in Python frontend and backend development, NLP, data science, and machine learning. Here are some tips to improve query performance:</p>
<h4 id="heading-efficiently-use-indexes">Efficiently use indexes</h4>
<p>Indexes help speed up query execution by allowing the database to quickly locate specific data. Identify frequently accessed columns and create indexes on them. For example, if a column is frequently used in WHERE clauses or JOIN conditions, consider creating an index on that column.</p>
<p>Example: Suppose we have a table called "products" with a column "name" frequently used in search queries. We can create an index on the "name" column to improve search performance.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Create an index on the "name" column</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'CREATE INDEX idx_products_name ON products(name)'</span>)
conn.close()
</code></pre>
<h4 id="heading-optimize-join-operations">Optimize JOIN operations</h4>
<p>JOIN operations can be resource-intensive. To enhance performance, minimize the number of JOIN operations and optimize the join conditions. Avoid unnecessary JOINs and use appropriate join types (e.g., INNER JOIN, LEFT JOIN) based on the relationship between tables.</p>
<p>Example: If we have two tables, "customers" and "orders," with a one-to-many relationship, use INNER JOIN to retrieve customers who have placed orders.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Retrieve customers who have placed orders using INNER JOIN</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'SELECT customers.name, orders.order_number FROM customers INNER JOIN orders ON customers.id = orders.customer_id'</span>)
result = cursor.fetchall()
conn.close()
</code></pre>
<h4 id="heading-use-appropriate-sql-clauses">Use appropriate SQL clauses</h4>
<p>Utilize SQL clauses like WHERE, GROUP BY, and HAVING to filter and aggregate data efficiently. Restrict the amount of data returned by applying filters early in the query.</p>
<p>Example: When retrieving customer data, use WHERE clauses to filter by specific criteria, such as age or location.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Retrieve customers older than 18 years</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'SELECT * FROM customers WHERE age &gt; 18'</span>)
result = cursor.fetchall()
conn.close()
</code></pre>
<h4 id="heading-minimize-data-retrieval">Minimize data retrieval</h4>
<p>Only retrieve the necessary columns and rows to reduce the amount of data transferred between the database and application. Avoid using SELECT * and limit the result set to the required data.</p>
<p>Example: Instead of retrieving all columns from the "users" table, specify only the required columns, such as name and email.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Retrieve only the required columns from the "users" table</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'SELECT name, email FROM users'</span>)
result = cursor.fetchall()
conn.close()
</code></pre>
<h4 id="heading-use-execution-plans">Use Execution Plans</h4>
<p>Analyzing and tuning database queries using execution plans is another valuable technique. Execution plans provide insights into how the database executes queries and can help identify performance bottlenecks. Examine the execution plan to ensure optimal query execution and identify areas for optimization.</p>
<p>Example: Use the EXPLAIN keyword in SQL to obtain the execution plan of a query and analyze it to identify potential performance improvements.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Retrieve the execution plan of a query</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'EXPLAIN SELECT * FROM products WHERE price &gt; 100'</span>)
result = cursor.fetchall()
conn.close()
</code></pre>
<p>Best practices for database indexing and transaction management are crucial to ensure data integrity and optimize performance:</p>
<h4 id="heading-identify-appropriate-columns-for-indexing">Identify appropriate columns for indexing</h4>
<p>Select columns that are frequently used in WHERE clauses, JOIN conditions, and ORDER BY clauses. Avoid over-indexing, as it can introduce overhead during data modification operations.</p>
<p>Example: If we often search for products by category, create an index on the "category" column to speed up these queries.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Create an index on the "category" column</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'CREATE INDEX idx_products_category ON products(category)'</span>)
conn.close()
</code></pre>
<h4 id="heading-manage-transactions-effectively">Manage transactions effectively</h4>
<p>Use transactions to group multiple database operations into a single logical unit. This ensures data consistency and allows for rollback in case of errors.</p>
<p>Example: When updating customer information, encapsulate the update operation within a transaction to guarantee that all changes are either committed or rolled back.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Update customer information within a transaction</span>
conn = sqlite3.connect(<span class="hljs-string">'example.db'</span>)
cursor = conn.cursor()
cursor.execute(<span class="hljs-string">'BEGIN'</span>)
cursor.execute(<span class="hljs-string">'UPDATE customers SET email = ? WHERE id = ?'</span>, (<span class="hljs-string">'new_email@example.com'</span>, <span class="hljs-number">1</span>))
cursor.execute(<span class="hljs-string">'COMMIT'</span>)
conn.close()
</code></pre>
<p>By following these practices, you can optimize SQL queries, analyze and tune execution plans, and implement effective database indexing and transaction management in Python frontend and backend development, NLP, data science, and machine learning projects.</p>
<h3 id="heading-advanced-topics-in-database-management">Advanced Topics in Database Management</h3>
<p>Exploring database sharding, replication, and clustering is essential for Python backend development. These strategies address scalability challenges by distributing data across multiple servers. </p>
<p>Sharding involves partitioning a database into smaller pieces, allowing for horizontal scaling. Replication creates multiple copies of a database to improve read performance and ensure data availability. Clustering connects servers to work as a single system, providing high availability and load balancing. </p>
<p>These strategies enable Python backend developers to build scalable, high-performance systems that can handle growing data requirements.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pymongo

<span class="hljs-comment"># Connect to the MongoDB database</span>
client = pymongo.MongoClient(<span class="hljs-string">'mongodb://localhost:27017/'</span>)

<span class="hljs-comment"># Enable sharding for the database</span>
admin_db = client.admin
admin_db.command(<span class="hljs-string">'enableSharding'</span>, <span class="hljs-string">'my_database'</span>)

<span class="hljs-comment"># Shard the collection based on a specific criterion</span>
admin_db.command(<span class="hljs-string">'shardCollection'</span>, <span class="hljs-string">'my_database.my_collection'</span>, key={<span class="hljs-string">'user_id'</span>: <span class="hljs-number">1</span>})

<span class="hljs-comment"># Close the connection</span>
client.close()
</code></pre>
<p>Databases are crucial for Python backend development, especially in big data and real-time applications. Python's simplicity and extensive library ecosystem make it an ideal choice for handling large amounts of data and enabling real-time data processing. </p>
<p>With databases, developers can efficiently manage and query big datasets, extract insights, and handle real-time data streams. Python's integration with databases like Hadoop, Apache Spark, and PostgreSQL, as well as real-time data processing frameworks like Apache Kafka and Redis, empowers developers to build scalable and responsive applications. </p>
<p>By understanding the role of databases in big data and real-time applications, Python backend developers can effectively handle data challenges and build efficient and reliable applications.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pyspark.sql <span class="hljs-keyword">import</span> SparkSession

<span class="hljs-comment"># Create a SparkSession</span>
spark = SparkSession.builder \\\\
    .appName(<span class="hljs-string">'Real-Time NLP Analysis'</span>) \\\\
    .getOrCreate()

<span class="hljs-comment"># Read data from a big data source, such as Apache Kafka</span>
df = spark \\\\
    .readStream \\\\
    .format(<span class="hljs-string">'kafka'</span>) \\\\
    .option(<span class="hljs-string">'kafka.bootstrap.servers'</span>, <span class="hljs-string">'localhost:9092'</span>) \\\\
    .option(<span class="hljs-string">'subscribe'</span>, <span class="hljs-string">'my_topic'</span>) \\\\
    .load()

<span class="hljs-comment"># Perform NLP analysis on the real-time data</span>
<span class="hljs-comment"># ...</span>

<span class="hljs-comment"># Write the results to a database for further analysis</span>
df.write \\\\
    .format(<span class="hljs-string">'database'</span>) \\\\
    .option(<span class="hljs-string">'url'</span>, <span class="hljs-string">'jdbc:mysql://localhost:3306/my_database'</span>) \\\\
    .option(<span class="hljs-string">'dbtable'</span>, <span class="hljs-string">'nlp_results'</span>) \\\\
    .mode(<span class="hljs-string">'append'</span>) \\\\
    .save()

<span class="hljs-comment"># Stop the SparkSession</span>
spark.stop()
</code></pre>
<p>Integrating Python applications with cloud-based database services is crucial for Python backend development. Cloud-based databases offer scalability, high availability, and easy management, making them ideal for handling the increasing demands of modern applications. By leveraging cloud-based databases, Python developers can focus on building robust and efficient backend systems without the need to manage infrastructure.</p>
<p>There are several benefits to using cloud-based database services in Python backend development. </p>
<p>First, they provide automatic backups and disaster recovery, ensuring data is protected and can be easily restored in case of any issues. </p>
<p>Second, these services offer built-in security features, such as encryption and access control, to protect sensitive data. Third, they enable seamless scalability, allowing applications to handle growing user bases and increasing data volumes without significant performance issues.</p>
<p>Cloud-based database services also provide built-in monitoring and analytics capabilities, giving you insights into the performance and usage of your applications. They also offer integration with other cloud services, such as serverless computing platforms and container orchestration tools, allowing you to build highly scalable and efficient application architectures.</p>
<p>Using cloud-based databases in Python backend development simplifies the deployment process. You can easily provision and configure database instances, manage database schemas, and perform backups and restores through simple APIs or web-based interfaces. This allows for faster development and deployment cycles, reducing time-to-market for new features and updates.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3

<span class="hljs-comment"># Connect to the Amazon RDS database</span>
client = boto3.client(<span class="hljs-string">'rds'</span>)

<span class="hljs-comment"># Create a new database instance</span>
client.create_db_instance(
    DBInstanceIdentifier=<span class="hljs-string">'my-instance'</span>,
    Engine=<span class="hljs-string">'mysql'</span>,
    DBInstanceClass=<span class="hljs-string">'db.t2.micro'</span>,
    AllocatedStorage=<span class="hljs-number">10</span>,
    MasterUsername=<span class="hljs-string">'admin'</span>,
    MasterUserPassword=<span class="hljs-string">'password'</span>
)

<span class="hljs-comment"># Connect to the database</span>
conn = pymysql.connect(
    host=<span class="hljs-string">'my-instance.abc123.us-west-2.rds.amazonaws.com'</span>,
    user=<span class="hljs-string">'admin'</span>,
    password=<span class="hljs-string">'password'</span>,
    database=<span class="hljs-string">'my_database'</span>
)

<span class="hljs-comment"># Perform database operations</span>
<span class="hljs-comment"># ...</span>

<span class="hljs-comment"># Close the connection</span>
conn.close()
</code></pre>
<p>By examining this example code, I hope you can better understand how to implement database sharding and how to leverage databases in big data and real-time applications. You should also understand how to integrate Python applications with cloud-based database services in Python frontend and backend development, NLP, data science, and machine learning projects.</p>
<h2 id="heading-security-and-authentication-in-back-end-development">Security and Authentication in Back-End Development</h2>
<p>In back-end development, security is essential for protecting data integrity and confidentiality. Neglecting security can lead to serious issues like data breaches and loss of user trust. To prevent this, a security-first approach in the development process is vital.</p>
<p>Let's briefly go over some key security practices with code examples.</p>
<h3 id="heading-user-authentication">User Authentication:</h3>
<p>Implementing strong authentication methods, such as passwords, tokens, and multi-factor authentication, is crucial to prevent unauthorized access. For instance, multi-factor authentication adds an additional security layer beyond just passwords.</p>
<p>Here's an example of implementing User Authentication in Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Password-based authentication</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">authenticate_user</span>(<span class="hljs-params">username, password</span>):</span>
    <span class="hljs-comment"># Check if username and password match in the database</span>
    <span class="hljs-comment"># Return True if authentication is successful, False otherwise</span>

<span class="hljs-comment"># Token-based authentication</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_token</span>(<span class="hljs-params">user_id</span>):</span>
    <span class="hljs-comment"># Generate a unique token for the user</span>
    <span class="hljs-comment"># Save the token in the database along with the user ID</span>
    <span class="hljs-comment"># Return the generated token</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verify_token</span>(<span class="hljs-params">token</span>):</span>
    <span class="hljs-comment"># Check if the token exists in the database</span>
    <span class="hljs-comment"># Return the associated user ID if the token is valid, None otherwise</span>

<span class="hljs-comment"># Multi-factor authentication</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_verification_code</span>(<span class="hljs-params">user_id</span>):</span>
    <span class="hljs-comment"># Generate and send a verification code to the user</span>
    <span class="hljs-comment"># Store the verification code in the database</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verify_verification_code</span>(<span class="hljs-params">user_id, code</span>):</span>
    <span class="hljs-comment"># Check if the provided code matches the one stored in the database</span>
    <span class="hljs-comment"># Return True if the code is valid, False otherwise</span>
</code></pre>
<h3 id="heading-user-authorization">User Authorization</h3>
<p>Managing user permissions ensures that individuals access only what they're allowed to, maintaining data security. For example, administrative users may access more sensitive data than regular users.</p>
<p>Here's a Python code sample of implementing User Authorization:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Role-based access control</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_user_permission</span>(<span class="hljs-params">user_id, resource_id</span>):</span>
    <span class="hljs-comment"># Query the database to check if the user has permission to access the resource</span>
    <span class="hljs-comment"># Return True if the user has permission, False otherwise</span>

<span class="hljs-comment"># Attribute-based access control</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_user_access</span>(<span class="hljs-params">user_id, resource_id</span>):</span>
    <span class="hljs-comment"># Query the database to retrieve the user's attributes and resource attributes</span>
    <span class="hljs-comment"># Apply access control policies based on the attributes</span>
    <span class="hljs-comment"># Return True if the user has access, False otherwise</span>
</code></pre>
<h3 id="heading-data-encryption">Data Encryption</h3>
<p>Protecting data in transit and at rest through encryption safeguards it from unauthorized access. Using robust algorithms like AES is a common practice.</p>
<p>Here's an example of Data Encryption in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">from</span> Crypto.Cipher <span class="hljs-keyword">import</span> AES

<span class="hljs-comment"># Encrypt data</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">encrypt_data</span>(<span class="hljs-params">data, key</span>):</span>
    cipher = AES.new(key, AES.MODE_ECB)
    encrypted_data = cipher.encrypt(data)
    <span class="hljs-keyword">return</span> encrypted_data

<span class="hljs-comment"># Decrypt data</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decrypt_data</span>(<span class="hljs-params">encrypted_data, key</span>):</span>
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted_data = cipher.decrypt(encrypted_data)
    <span class="hljs-keyword">return</span> decrypted_data
</code></pre>
<h3 id="heading-secure-communication-protocols">Secure Communication Protocols</h3>
<p>Utilizing HTTPS and TLS ensures encrypted and secure data transmission, especially when handling sensitive user information.</p>
<p>Here's an example of a Secure Communication Protocol implemented in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests

<span class="hljs-comment"># Make a secure HTTPS request</span>
response = requests.get(<span class="hljs-string">'&lt;https://example.com&gt;'</span>)

<span class="hljs-comment"># Use TLS/SSL certificates for secure communication</span>
app.run(ssl_context=<span class="hljs-string">'adhoc'</span>)
</code></pre>
<h3 id="heading-secure-storage-and-data-handling">Secure Storage and Data Handling</h3>
<p>Encrypting stored data and employing secure storage technologies are necessary for maintaining data confidentiality.</p>
<p>Here's an example of Secure Storage and Data Handling in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> bcrypt

<span class="hljs-comment"># Hash passwords for secure storage</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hash_password</span>(<span class="hljs-params">password</span>):</span>
    hashed_password = bcrypt.hashpw(password.encode(<span class="hljs-string">'utf-8'</span>), bcrypt.gensalt())
    <span class="hljs-keyword">return</span> hashed_password

<span class="hljs-comment"># Verify hashed passwords</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verify_password</span>(<span class="hljs-params">password, hashed_password</span>):</span>
    <span class="hljs-keyword">return</span> bcrypt.checkpw(password.encode(<span class="hljs-string">'utf-8'</span>), hashed_password)
</code></pre>
<h3 id="heading-key-management-and-access-controls">Key Management and Access Controls</h3>
<p>Proper management of encryption keys and access credentials prevents unauthorized resource access. Role-based access control is an effective strategy here.</p>
<p>Here's an example of Key Management and Access Controls in Python:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Key management</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_encryption_key</span>():</span>
    <span class="hljs-comment"># Generate a secure encryption key</span>
    <span class="hljs-comment"># Store the key securely, such as in a key management system or hardware security module</span>

<span class="hljs-comment"># Access controls</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_access</span>(<span class="hljs-params">user_id, resource_id</span>):</span>
    <span class="hljs-comment"># Query the database to check if the user has access to the resource based on their role or attributes</span>
    <span class="hljs-comment"># Return True if the user has access, False otherwise</span>
</code></pre>
<h3 id="heading-regular-security-testing">Regular Security Testing</h3>
<p>Conducting audits and penetration testing helps identify and rectify vulnerabilities. Adhering to industry standards and regulations is also crucial for system security.</p>
<p>Here's an example of how to perform regular Security Testing in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> unittest
<span class="hljs-keyword">from</span> unittest.mock <span class="hljs-keyword">import</span> patch
<span class="hljs-keyword">from</span> app <span class="hljs-keyword">import</span> app

<span class="hljs-comment"># Example unit test with mock patching</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">APITestCase</span>(<span class="hljs-params">unittest.TestCase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_secure_endpoint</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">with</span> patch(<span class="hljs-string">'app.authenticate_user'</span>) <span class="hljs-keyword">as</span> mock_authenticate:
            mock_authenticate.return_value = <span class="hljs-literal">True</span>
            response = app.test_client().get(<span class="hljs-string">'/secure-endpoint'</span>)
            self.assertEqual(response.status_code, <span class="hljs-number">200</span>)
            self.assertEqual(response.data, <span class="hljs-string">b'Success'</span>)
</code></pre>
<p>Remember to customize and adapt all these code snippets to your specific application's needs. These examples provide a starting point for implementing the security practices in your back-end development projects.</p>
<h3 id="heading-stay-informed">Stay Informed</h3>
<p>Keeping up with the latest security trends and threats enables continuous improvement in security practices.</p>
<p>Security in back-end development involves robust authentication, careful user authorization, data encryption, secure protocols, vigilant storage practices, stringent access controls, ongoing testing, and staying current with security advancements. These measures collectively ensure the creation of secure and trustworthy applications.</p>
<h2 id="heading-fundamentals-of-web-security">Fundamentals of Web Security</h2>
<p>In back-end development, a deep understanding of security threats is key to implementing effective measures. Embracing a security-first approach ensures data integrity and confidentiality.</p>
<p>Key security challenges include:</p>
<h3 id="heading-cross-site-scripting-xss">Cross-Site Scripting (XSS)</h3>
<p>Cross-Site Scripting attacks occur when an attacker manages to inject malicious scripts into content that is then served to a user. These scripts execute within the victim's browser under the guise of a trusted site, potentially stealing cookies, session tokens, or other sensitive information that can be used to impersonate the victim.</p>
<h4 id="heading-mitigation-strategies">Mitigation Strategies:</h4>
<p><strong>Sanitizing User Inputs:</strong> Ensure that all user-provided data is sanitized, which means filtering out any potentially malicious content before it's used or displayed on your site. </p>
<p>This often involves stripping out HTML tags or JavaScript from inputs that are not expected to contain such content.</p>
<p><strong>Using Output Encoding:</strong> When displaying user-generated content, employ output encoding techniques. </p>
<p>This involves converting special characters into their HTML or URL encoded equivalents so that they are rendered harmless. For example, characters like <code>&lt;</code>, <code>&gt;</code>, and <code>"</code> are converted to <code>&amp;lt;</code>, <code>&amp;gt;</code>, and <code>&amp;quot;</code>, respectively.</p>
<h3 id="heading-sql-injection">SQL Injection</h3>
<p>SQL Injection attacks involve inserting or "injecting" a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data, execute administrative operations on the database, and in some cases, issue commands to the operating system.</p>
<h4 id="heading-mitigation-strategies-1">Mitigation Strategies:</h4>
<p><strong>Parameterized Queries:</strong> Use parameterized queries (also known as prepared statements) whenever interacting with the database. This approach allows the database to distinguish between code and data, regardless of the input content.</p>
<p><strong>Avoid Direct SQL Query Concatenation:</strong> Never build SQL queries by directly concatenating user input with SQL code. This practice is prone to SQL injection because it treats user input as part of the SQL syntax. Always use safe methods provided by your database access libraries to parameterize inputs.</p>
<h3 id="heading-cross-site-request-forgery-csrf">Cross-Site Request Forgery (CSRF)</h3>
<p>Cross-Site Request Forgery is an attack that tricks the victim into executing unwanted actions on a web application in which they're currently authenticated. </p>
<p>If the victim is a regular user, a successful CSRF attack can force them to perform state-changing requests like transferring funds, changing their email address, and so on. If the victim is an administrative account, CSRF can compromise the entire web application.</p>
<h4 id="heading-mitigation-strategies-2">Mitigation Strategies:</h4>
<p><strong>Use CSRF Tokens:</strong> A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client. When the next request is made, the server checks the submitted token against the one it issued and rejects the request if the values do not match.</p>
<p><strong>SameSite Cookie Attribute:</strong> Utilize the <code>SameSite</code> attribute in cookies, which tells the browser to only send the cookie in requests originating from the same domain as the target domain. </p>
<p>This can effectively prevent CSRF attacks by ensuring that authenticated session cookies are not sent along with requests initiated by third-party websites.</p>
<p>Implementing these strategies can significantly enhance the security of web applications by mitigating some of the most common and impactful security vulnerabilities.</p>
<p>Regular security audits and staying updated with the latest trends are crucial for ongoing protection. In Python development, utilizing frameworks like Flask-Security or Django’s authentication features helps in secure user authentication. They offer password hashing, token authentication, and multi-factor authentication support.</p>
<p>Let's get into each of these security risks in a bit more detail with some code examples.</p>
<p>Cross-Site Scripting (XSS):</p>
<pre><code class="lang-python"><span class="hljs-comment"># Sanitizing user inputs to prevent XSS attacks</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sanitize_input</span>(<span class="hljs-params">input_string</span>):</span>
    <span class="hljs-comment"># Remove HTML tags and special characters from the input string</span>
    sanitized_string = input_string.replace(<span class="hljs-string">'&lt;'</span>, <span class="hljs-string">'&amp;lt;'</span>).replace(<span class="hljs-string">'&gt;'</span>, <span class="hljs-string">'&amp;gt;'</span>)
    <span class="hljs-keyword">return</span> sanitized_string

<span class="hljs-comment"># Using output encoding to prevent XSS attacks</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">output_encode</span>(<span class="hljs-params">input_string</span>):</span>
    <span class="hljs-comment"># Encode special characters to their HTML entity representation</span>
    encoded_string = html.escape(input_string)
    <span class="hljs-keyword">return</span> encoded_string
</code></pre>
<p>SQL Injection:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Using parameterized queries to prevent SQL injection</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_user</span>(<span class="hljs-params">username</span>):</span>
    conn = sqlite3.connect(<span class="hljs-string">'database.db'</span>)
    cursor = conn.cursor()

    query = <span class="hljs-string">"SELECT * FROM Users WHERE username = ?"</span>
    cursor.execute(query, (username,))
    user = cursor.fetchone()

    conn.close()

    <span class="hljs-keyword">return</span> user
</code></pre>
<p>Cross-Site Request Forgery (CSRF):</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, render_template, request, session
<span class="hljs-keyword">import</span> secrets

app = Flask(__name__)
app.secret_key = secrets.token_hex(<span class="hljs-number">16</span>)

<span class="hljs-meta">@app.route('/login', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">login</span>():</span>
    <span class="hljs-comment"># Generate and store a CSRF token in the session</span>
    session[<span class="hljs-string">'csrf_token'</span>] = secrets.token_hex(<span class="hljs-number">16</span>)

    <span class="hljs-comment"># Validate the CSRF token sent in the request</span>
    <span class="hljs-keyword">if</span> session[<span class="hljs-string">'csrf_token'</span>] != request.form[<span class="hljs-string">'csrf_token'</span>]:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Invalid CSRF token"</span>

    <span class="hljs-comment"># Continue with the login process</span>

    <span class="hljs-keyword">return</span> <span class="hljs-string">"Login successful"</span>

<span class="hljs-meta">@app.route('/form', methods=['GET'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">form</span>():</span>
    <span class="hljs-comment"># Generate a CSRF token and render the form template</span>
    csrf_token = secrets.token_hex(<span class="hljs-number">16</span>)
    <span class="hljs-keyword">return</span> render_template(<span class="hljs-string">'form.html'</span>, csrf_token=csrf_token)
</code></pre>
<p>Remember to customize and adapt the code snippets to your specific application's needs. These examples provide a starting point for implementing security measures against XSS, SQL injection, and CSRF attacks in your back-end development projects.</p>
<h2 id="heading-user-authentication-1">User Authentication</h2>
<p>User authentication is a critical process in ensuring the security of your application. It involves verifying the identity of users before granting them access to protected resources. There are several authentication mechanisms you can implement, such as passwords, tokens, and multi-factor authentication.</p>
<p>For passwords, it is important to enforce strong password policies that require a combination of uppercase and lowercase letters, numbers, and special characters. Also, consider implementing features like password complexity checks and password expiration to enhance security. An example of a strong password would be "P@ssw0rd123".</p>
<p>Tokens are another commonly used authentication mechanism. They are unique strings that are generated and issued to users upon successful authentication. Tokens can be stored securely and used for subsequent requests to authenticate the user. </p>
<p>An example of a token-based authentication flow is using JSON Web Tokens (JWT), where a user logs in and receives a token that is included in subsequent requests for authentication.</p>
<p>Multi-factor authentication (MFA) adds an extra layer of security by requiring users to provide additional verification, such as a one-time password sent to their mobile device or a fingerprint scan. Implementing MFA can significantly reduce the risk of unauthorized access to user accounts. </p>
<p>For example, when a user logs in, they might be prompted to enter a verification code received via SMS in addition to their password.</p>
<p>To ensure secure authentication, consider the following best practices:</p>
<ul>
<li>Implement secure storage for passwords and tokens, such as hashing passwords using strong hashing algorithms like bcrypt or Argon2.</li>
<li>Utilize encryption for transmitting sensitive authentication data, such as using HTTPS for secure communication.</li>
<li>Regularly review and update authentication mechanisms to address any known vulnerabilities.</li>
</ul>
<p>Remember, user authentication is a crucial aspect of your application's security. By implementing robust authentication mechanisms and following best practices, you can protect user accounts and maintain the trust of your users.</p>
<p><strong>User Authentication:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> bcrypt
<span class="hljs-keyword">import</span> jwt

<span class="hljs-comment"># Password-based authentication</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">authenticate_user</span>(<span class="hljs-params">username, password</span>):</span>
    <span class="hljs-comment"># Retrieve the user's hashed password from the database</span>
    hashed_password = get_hashed_password(username)

    <span class="hljs-comment"># Verify the provided password against the hashed password</span>
    <span class="hljs-keyword">if</span> bcrypt.checkpw(password.encode(<span class="hljs-string">'utf-8'</span>), hashed_password):
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

<span class="hljs-comment"># Token-based authentication</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_token</span>(<span class="hljs-params">user_id</span>):</span>
    <span class="hljs-comment"># Generate a JSON Web Token (JWT) with the user ID as the payload</span>
    token = jwt.encode({<span class="hljs-string">'user_id'</span>: user_id}, <span class="hljs-string">'secret_key'</span>, algorithm=<span class="hljs-string">'HS256'</span>)
    <span class="hljs-keyword">return</span> token

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verify_token</span>(<span class="hljs-params">token</span>):</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment"># Verify and decode the JWT</span>
        decoded_token = jwt.decode(token, <span class="hljs-string">'secret_key'</span>, algorithms=[<span class="hljs-string">'HS256'</span>])
        user_id = decoded_token[<span class="hljs-string">'user_id'</span>]
        <span class="hljs-keyword">return</span> user_id
    <span class="hljs-keyword">except</span> jwt.InvalidTokenError:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>

<span class="hljs-comment"># Multi-factor authentication</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_verification_code</span>(<span class="hljs-params">user_id</span>):</span>
    <span class="hljs-comment"># Generate and send a verification code to the user</span>
    verification_code = generate_verification_code()
    store_verification_code(user_id, verification_code)
    send_sms(user_id, verification_code)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verify_verification_code</span>(<span class="hljs-params">user_id, code</span>):</span>
    <span class="hljs-comment"># Retrieve the stored verification code for the user</span>
    stored_code = get_verification_code(user_id)

    <span class="hljs-comment"># Check if the provided code matches the stored code</span>
    <span class="hljs-keyword">if</span> code == stored_code:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p>Remember to customize and adapt the code snippet to your specific application's needs. This example provides a starting point for implementing user authentication in your back-end development projects.</p>
<h2 id="heading-user-authorization-1">User Authorization</h2>
<p>Defining user permissions and access levels is a crucial aspect of user authorization. In Python frontend and backend development, you can achieve this by implementing role-based access control (RBAC) or attribute-based access control (ABAC) mechanisms.</p>
<p>With RBAC, you assign roles to users based on their responsibilities or job titles. For example, you may have roles such as "admin," "manager," and "user." Each role has a predefined set of permissions that determine what actions a user with that role can perform. By assigning appropriate roles to users, you can control their access to different parts of the application.</p>
<p>On the other hand, ABAC takes a more fine-grained approach by considering various attributes of the user, the resource being accessed, and the context in which the access request is made. Attributes like user location, time of day, or user department can influence access decisions. For instance, you can define policies that allow only users from a specific department to access certain sensitive data.</p>
<p>To effectively manage user authorization, consider using a well-established authentication and authorization framework like Django's built-in authentication system or Flask-Security. These frameworks provide convenient methods and decorators to handle user permissions and access control.</p>
<p>Remember, authentication and authorization are distinct but interconnected concepts. While authentication verifies the identity of users, authorization determines what actions they are allowed to perform. Understanding the difference is crucial for building secure and reliable applications.</p>
<p>Example:</p>
<p>In a Python web application, let's say you have defined three roles: "admin," "manager," and "user."</p>
<ul>
<li>The "admin" role has permissions to perform administrative tasks such as creating and managing users, modifying system settings, and accessing sensitive data.</li>
<li>The "manager" role can perform tasks related to managing projects, assigning tasks to team members, and generating reports.</li>
<li>The "user" role has limited permissions and can perform basic actions like creating and updating their own profile, viewing project details, and submitting feedback.</li>
</ul>
<p>By assigning the appropriate role to each user, you ensure that they have access to the necessary features and data based on their responsibilities and level of authority within the application.</p>
<p><strong>Role-based access control (RBAC) example:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># Define roles and their corresponding permissions</span>
ROLES = {
    <span class="hljs-string">'admin'</span>: [<span class="hljs-string">'create_user'</span>, <span class="hljs-string">'delete_user'</span>, <span class="hljs-string">'modify_settings'</span>, <span class="hljs-string">'access_sensitive_data'</span>],
    <span class="hljs-string">'manager'</span>: [<span class="hljs-string">'manage_projects'</span>, <span class="hljs-string">'assign_tasks'</span>, <span class="hljs-string">'generate_reports'</span>],
    <span class="hljs-string">'user'</span>: [<span class="hljs-string">'update_profile'</span>, <span class="hljs-string">'view_project_details'</span>, <span class="hljs-string">'submit_feedback'</span>]
}

<span class="hljs-comment"># Check user's role and perform actions based on permissions</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">perform_action</span>(<span class="hljs-params">user_role, action</span>):</span>
    <span class="hljs-keyword">if</span> user_role <span class="hljs-keyword">in</span> ROLES:
        <span class="hljs-keyword">if</span> action <span class="hljs-keyword">in</span> ROLES[user_role]:
            <span class="hljs-comment"># Perform the action</span>
            print(<span class="hljs-string">f"Performing <span class="hljs-subst">{action}</span> as <span class="hljs-subst">{user_role}</span>"</span>)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"Access denied. <span class="hljs-subst">{user_role}</span> does not have permission to perform <span class="hljs-subst">{action}</span>"</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"Invalid role: <span class="hljs-subst">{user_role}</span>"</span>)

<span class="hljs-comment"># Example usage</span>
perform_action(<span class="hljs-string">'admin'</span>, <span class="hljs-string">'create_user'</span>)  <span class="hljs-comment"># Performing create_user as admin</span>
perform_action(<span class="hljs-string">'manager'</span>, <span class="hljs-string">'delete_user'</span>)  <span class="hljs-comment"># Access denied. manager does not have permission to perform delete_user</span>
perform_action(<span class="hljs-string">'user'</span>, <span class="hljs-string">'update_profile'</span>)  <span class="hljs-comment"># Performing update_profile as user</span>
</code></pre>
<p><strong>Attribute-based access control (ABAC) example:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># Define user attributes and their values</span>
USER_ATTRIBUTES = {
    <span class="hljs-string">'user1'</span>: {<span class="hljs-string">'department'</span>: <span class="hljs-string">'HR'</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'office1'</span>},
    <span class="hljs-string">'user2'</span>: {<span class="hljs-string">'department'</span>: <span class="hljs-string">'IT'</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'office2'</span>},
    <span class="hljs-string">'user3'</span>: {<span class="hljs-string">'department'</span>: <span class="hljs-string">'Finance'</span>, <span class="hljs-string">'location'</span>: <span class="hljs-string">'office1'</span>}
}

<span class="hljs-comment"># Define resource attributes and their values</span>
RESOURCE_ATTRIBUTES = {
    <span class="hljs-string">'resource1'</span>: {<span class="hljs-string">'department'</span>: <span class="hljs-string">'HR'</span>},
    <span class="hljs-string">'resource2'</span>: {<span class="hljs-string">'department'</span>: <span class="hljs-string">'IT'</span>},
    <span class="hljs-string">'resource3'</span>: {<span class="hljs-string">'department'</span>: <span class="hljs-string">'Finance'</span>}
}

<span class="hljs-comment"># Check user's attributes and resource attributes to determine access</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_access</span>(<span class="hljs-params">user_id, resource_id</span>):</span>
    <span class="hljs-keyword">if</span> user_id <span class="hljs-keyword">in</span> USER_ATTRIBUTES <span class="hljs-keyword">and</span> resource_id <span class="hljs-keyword">in</span> RESOURCE_ATTRIBUTES:
        user_attributes = USER_ATTRIBUTES[user_id]
        resource_attributes = RESOURCE_ATTRIBUTES[resource_id]

        <span class="hljs-keyword">if</span> user_attributes[<span class="hljs-string">'department'</span>] == resource_attributes[<span class="hljs-string">'department'</span>]:
            <span class="hljs-comment"># Grant access</span>
            print(<span class="hljs-string">f"Access granted for <span class="hljs-subst">{user_id}</span> to <span class="hljs-subst">{resource_id}</span>"</span>)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"Access denied. <span class="hljs-subst">{user_id}</span> does not have access to <span class="hljs-subst">{resource_id}</span>"</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"Invalid user ID or resource ID"</span>)

<span class="hljs-comment"># Example usage</span>
check_access(<span class="hljs-string">'user1'</span>, <span class="hljs-string">'resource1'</span>)  <span class="hljs-comment"># Access granted for user1 to resource1</span>
check_access(<span class="hljs-string">'user2'</span>, <span class="hljs-string">'resource3'</span>)  <span class="hljs-comment"># Access denied. user2 does not have access to resource3</span>
check_access(<span class="hljs-string">'user3'</span>, <span class="hljs-string">'resource2'</span>)  <span class="hljs-comment"># Access denied. user3 does not have access to resource2</span>
</code></pre>
<p>Remember to customize and adapt the code snippets to your specific application's needs. These examples provide a starting point for implementing role-based access control (RBAC) and attribute-based access control (ABAC) mechanisms in your Python backend development projects.</p>
<h2 id="heading-encryption-techniques">Encryption Techniques</h2>
<p>In Python frontend and backend development, encryption plays a crucial role in safeguarding data. There are different types of encryption to consider: in transit, at rest, and end-to-end.</p>
<h3 id="heading-in-transit-encryption">In Transit Encryption</h3>
<p>When data is being transmitted between different systems or over a network, it is important to ensure that it is encrypted. This prevents unauthorized access and eavesdropping on sensitive information. </p>
<p>Implementing secure communication protocols like HTTPS and TLS is essential for encrypting data in transit. For example, you can use the <code>requests</code> library in Python to make API calls using HTTPS, ensuring secure transmission of data.</p>
<h3 id="heading-at-rest-encryption">At Rest Encryption</h3>
<p>When data is stored in databases or on physical storage devices, it should be encrypted to protect it from unauthorized access. Choosing the right encryption algorithms and implementing them effectively is crucial for ensuring the security of the stored data. </p>
<p>For instance, in Python, you can use libraries like <code>cryptography</code> to encrypt sensitive data before storing it in a database. By encrypting data at rest, even if the storage medium is compromised, the data remains protected.</p>
<h3 id="heading-end-to-end-encryption">End-to-End Encryption</h3>
<p>End-to-end encryption provides an additional layer of security by ensuring that data remains encrypted throughout its entire journey, from the sender to the recipient. This means that only the intended recipients can decrypt and access the data. </p>
<p>For example, in a messaging application, end-to-end encryption ensures that only the sender and the intended recipient can read the messages, even if they pass through intermediate servers. </p>
<p>Implementing end-to-end encryption requires careful consideration of cryptographic protocols and key management practices.</p>
<p>Choosing the right encryption algorithms and implementing them effectively is crucial for maintaining the security of your application. It is recommended to use widely accepted and tested encryption algorithms like AES (Advanced Encryption Standard). Also, regularly updating encryption libraries and frameworks to the latest versions helps address any known vulnerabilities.</p>
<p>Remember, encryption is an important aspect of data security in both frontend and backend development. By implementing encryption techniques, you can protect sensitive data and ensure the confidentiality and integrity of your application's information.</p>
<h2 id="heading-secure-communication-protocols-1">Secure Communication Protocols</h2>
<p>In Python frontend and backend development, ensuring secure data transmission is vital to protect sensitive information. Two key practices for achieving this are utilizing HTTPS and TLS.</p>
<h3 id="heading-use-https">Use HTTPS</h3>
<p>When transmitting data over networks, it is crucial to use HTTPS (Hypertext Transfer Protocol Secure). HTTPS encrypts the data being transmitted, preventing unauthorized access and ensuring data integrity. </p>
<p>By implementing HTTPS, you can secure the communication between clients and servers, safeguarding sensitive user information. </p>
<p>For example, in a Python web application, you can configure your server to use HTTPS by obtaining and installing an SSL/TLS certificate.</p>
<h3 id="heading-protect-api-endpoints-and-backend-services">Protect API Endpoints and Backend Services</h3>
<p>It is essential to secure API endpoints and backend services to prevent unauthorized access and data breaches. Implementing authentication and authorization mechanisms is crucial here. </p>
<p>For instance, in Python backend development, you can use frameworks like Flask or Django to implement token-based authentication, where users are issued tokens upon successful authentication. These tokens are then included in subsequent requests to authenticate the user and grant access to protected endpoints.</p>
<p>For example, in a Python backend application, let's consider an API endpoint that allows users to retrieve sensitive user data. </p>
<p>To protect this endpoint, you can implement authentication using JWT (JSON Web Tokens). When a user successfully logs in, they receive a JWT that contains their identity and authorization claims. For subsequent requests to the sensitive endpoint, the user includes this JWT in the request headers. The backend server then validates and verifies the token before granting access to the protected data.</p>
<p>By utilizing HTTPS and implementing robust authentication mechanisms, such as token-based authentication, you can ensure secure data transmission and protect API endpoints and backend services in your Python applications.</p>
<p>Remember, adopting these security practices in Python frontend and backend development is crucial for safeguarding sensitive information and maintaining the trust of your users.</p>
<h2 id="heading-secure-storage-and-data-handling-1">Secure Storage and Data Handling</h2>
<p>In Python frontend and backend development, ensuring the secure storage of sensitive data and preventing data leaks are critical considerations. By following best practices, you can enhance data integrity and safeguard confidential information.</p>
<h3 id="heading-best-practices-for-storing-sensitive-data">Best Practices for Storing Sensitive Data</h3>
<p>When it comes to storing sensitive data, several best practices can help maintain its security:</p>
<ol>
<li><strong>Data Encryption</strong>: Encrypting sensitive data before storing it adds an extra layer of protection. Utilize cryptographic algorithms like AES (Advanced Encryption Standard) to ensure secure storage. For example, in Python, you can use libraries like <code>cryptography</code> to implement encryption in your application.</li>
<li><strong>Secure Key Management</strong>: Properly managing encryption keys is crucial for data security. Store keys securely using key management systems or hardware security modules (HSMs) to prevent unauthorized access. Maintain a well-defined key rotation policy to minimize the risk of key compromise.</li>
<li><strong>Access Controls</strong>: Implement robust access controls to restrict data access to authorized personnel only. Use role-based access control (RBAC) or attribute-based access control (ABAC) mechanisms to enforce granular permissions. Regularly review and update access control policies to align with changing requirements.</li>
<li><strong>Secure Backup and Disaster Recovery</strong>: Regularly back up sensitive data and store backup copies securely. Test the restoration process to ensure data availability in case of emergencies. Implement disaster recovery strategies to minimize the impact of data breaches or system failures.</li>
</ol>
<p><strong>Example:</strong></p>
<p>Let's consider an example in Python backend development. Suppose you are developing a web application that handles sensitive user data, such as personal information. To ensure secure storage, you can employ the following practices:</p>
<ul>
<li>Encrypt the sensitive user data using AES encryption before storing it in the database. This ensures that even if the database is compromised, the data remains protected.</li>
<li>Implement secure key management by using a key management system to securely store and manage encryption keys. This prevents unauthorized access to the keys, enhancing overall data security.</li>
<li>Apply access controls to restrict data access to authorized users only. For example, implement RBAC to assign different roles to users and grant them permissions based on their responsibilities and level of authority.</li>
<li>Regularly back up the encrypted data and store the backup copies securely. Test the restoration process to ensure data availability in case of data loss or system failures.</li>
</ul>
<p>By following these best practices, you can ensure the secure storage of sensitive data in your Python application, minimizing the risk of data leaks and maintaining the confidentiality of user information.</p>
<h3 id="heading-how-to-prevent-data-leaks-and-ensure-data-integrity">How to prevent data leaks and ensure data integrity</h3>
<p>Preventing data leaks and maintaining data integrity are vital aspects of data security. Consider the following practices:</p>
<ol>
<li><strong>Input Validation</strong>: Validate all user inputs to prevent common vulnerabilities like SQL injection and cross-site scripting (XSS). Implement server-side input validation and sanitize user inputs to mitigate the risk of code injection attacks.</li>
<li><strong>Secure File Uploads</strong>: Implement strict file upload validation to prevent unauthorized execution of malicious files. Validate file types, limit file sizes, and store uploaded files in a secure location to prevent unauthorized access or execution.</li>
<li><strong>Secure Logging</strong>: Log events and errors securely to prevent sensitive information from being exposed. Avoid logging sensitive data like passwords or personally identifiable information (PII). Utilize secure logging frameworks and ensure log files are protected from unauthorized access.</li>
<li><strong>Secure Configuration</strong>: Maintain secure configurations for your application, server, and related components. Disable unnecessary services, apply security patches promptly, and follow security best practices for server and application configurations.</li>
</ol>
<p><strong>Example:</strong></p>
<p>Let's illustrate these practices with a Python frontend development example. Suppose you are developing a web application that accepts user inputs and performs database operations. </p>
<p>To prevent data leaks and ensure data integrity, you can adopt the following measures:</p>
<ul>
<li>Implement server-side input validation to validate and sanitize user inputs. This prevents common vulnerabilities like SQL injection and helps maintain data integrity.</li>
<li>Apply strict file upload validation to ensure that only allowed file types and sizes are accepted. Store uploaded files outside the web root directory to prevent unauthorized access and execution.</li>
<li>Log events and errors securely using a logging framework that supports secure logging practices. Avoid logging sensitive information, and ensure log files are protected from unauthorized access.</li>
<li>Maintain secure configurations for your application and server. Regularly update and patch software components, disable unnecessary services, and follow security best practices for configurations.</li>
</ul>
<p>By implementing these practices, you can significantly reduce the risk of data leaks and maintain the integrity of your application's data in Python frontend development.</p>
<p>Remember, ensuring secure data storage and preventing data leaks are critical for maintaining the trust of your users and protecting sensitive information. By following these best practices, you can enhance data security in your Python frontend and backend development projects.</p>
<p>Here are some code examples that show various ways to protect your Python applications:</p>
<p><strong>User Authorization:</strong></p>
<pre><code class="lang-python"><span class="hljs-comment"># Role-based access control</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_user_permission</span>(<span class="hljs-params">user_id, resource_id</span>):</span>
    <span class="hljs-comment"># Query the database to check if the user has permission to access the resource</span>
    user_role = get_user_role(user_id)
    resource_permissions = get_resource_permissions(resource_id)

    <span class="hljs-keyword">if</span> user_role <span class="hljs-keyword">in</span> resource_permissions:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

<span class="hljs-comment"># Attribute-based access control</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_user_access</span>(<span class="hljs-params">user_id, resource_id</span>):</span>
    <span class="hljs-comment"># Query the database to retrieve the user's attributes and resource attributes</span>
    user_attributes = get_user_attributes(user_id)
    resource_attributes = get_resource_attributes(resource_id)

    <span class="hljs-comment"># Apply access control policies based on the attributes</span>
    <span class="hljs-keyword">if</span> user_attributes[<span class="hljs-string">'department'</span>] == resource_attributes[<span class="hljs-string">'department'</span>]:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
</code></pre>
<p><strong>Data Encryption:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">from</span> Crypto.Cipher <span class="hljs-keyword">import</span> AES

<span class="hljs-comment"># Encrypt data</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">encrypt_data</span>(<span class="hljs-params">data, key</span>):</span>
    cipher = AES.new(key, AES.MODE_ECB)
    encrypted_data = cipher.encrypt(data)
    <span class="hljs-keyword">return</span> encrypted_data

<span class="hljs-comment"># Decrypt data</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decrypt_data</span>(<span class="hljs-params">encrypted_data, key</span>):</span>
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted_data = cipher.decrypt(encrypted_data)
    <span class="hljs-keyword">return</span> decrypted_data
</code></pre>
<p><strong>Secure Communication Protocols:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests

<span class="hljs-comment"># Make a secure HTTPS request</span>
response = requests.get(<span class="hljs-string">'&lt;https://example.com&gt;'</span>)

<span class="hljs-comment"># Use TLS/SSL certificates for secure communication</span>
app.run(ssl_context=<span class="hljs-string">'adhoc'</span>)
</code></pre>
<p><strong>Secure Storage and Data Handling:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> bcrypt

<span class="hljs-comment"># Hash passwords for secure storage</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hash_password</span>(<span class="hljs-params">password</span>):</span>
    hashed_password = bcrypt.hashpw(password.encode(<span class="hljs-string">'utf-8'</span>), bcrypt.gensalt())
    <span class="hljs-keyword">return</span> hashed_password

<span class="hljs-comment"># Verify hashed passwords</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">verify_password</span>(<span class="hljs-params">password, hashed_password</span>):</span>
    <span class="hljs-keyword">return</span> bcrypt.checkpw(password.encode(<span class="hljs-string">'utf-8'</span>), hashed_password)
</code></pre>
<p>Remember to customize and adapt the code snippets to your specific application's needs. These examples provide a starting point for implementing user authentication, user authorization, data encryption, secure communication protocols, and secure storage and data handling in your back-end development projects.</p>
<h2 id="heading-key-management-and-access-controls-1">Key Management and Access Controls</h2>
<p>In Python front-end and back-end development, secure key management and robust access control are crucial for data security.</p>
<p>Key management involves storing encryption keys in secure locations like key management systems or hardware security modules (HSMs). Regular key rotation and limiting key access to authorized personnel are also essential. Implement strong authentication, such as multi-factor authentication (MFA), to access these keys.</p>
<p>For access control, define granular policies based on user roles and responsibilities, using systems like role-based access control (RBAC) or attribute-based access control (ABAC). Regularly update these policies and combine them with strong authentication methods, including passwords, tokens, or MFA, to safeguard sensitive resources.</p>
<p>For instance, in a Python web application handling sensitive user data or patient records, these practices ensure that only authorized users can access and decrypt critical information, maintaining data integrity and user trust.</p>
<p>In summary, managing encryption keys securely and implementing effective access control are fundamental in Python development to protect data and maintain application integrity.</p>
<h3 id="heading-secure-key-management">Secure Key Management:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> cryptography
<span class="hljs-keyword">from</span> cryptography.fernet <span class="hljs-keyword">import</span> Fernet

<span class="hljs-comment"># Generate a new encryption key</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_key</span>():</span>
    key = Fernet.generate_key()
    <span class="hljs-keyword">return</span> key

<span class="hljs-comment"># Store the encryption key securely</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">store_key</span>(<span class="hljs-params">key</span>):</span>
    <span class="hljs-comment"># Store the key in a key management system or hardware security module (HSM)</span>
    <span class="hljs-comment"># Follow best practices for securing the key storage</span>

<span class="hljs-comment"># Retrieve the encryption key</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">retrieve_key</span>():</span>
    <span class="hljs-comment"># Retrieve the key from the secure storage</span>
    key = get_key_from_storage()
    <span class="hljs-keyword">return</span> key

<span class="hljs-comment"># Example usage</span>
key = generate_key()
store_key(key)
key = retrieve_key()
</code></pre>
<p>And you can always go back to the examples of Role-Based Access Control (RBAC) and Attribute-Based Access Control (ABAC) above if you need to review those security processes.</p>
<p>Remember to customize and adapt the code snippets to your specific application's needs. These examples provide a starting point for implementing secure key management and access control mechanisms in your Python back-end development projects.</p>
<h2 id="heading-how-to-prepare-for-a-back-end-python-developer-job">How to Prepare for a Back-end Python Developer Job</h2>
<p>Becoming a back-end Python developer goes beyond learning Python and its frameworks; it involves showcasing your skills and solving complex issues through a well-crafted portfolio. This subchapter guides you on preparing for a back-end Python developer role, emphasizing the importance of a portfolio that reflects your technical skills and problem-solving capabilities.</p>
<p>Your portfolio is crucial—it demonstrates your expertise, creativity, and commitment to Python back-end development. Choose projects that mirror your career goals and exhibit essential skills like database management, API development, and system integration.</p>
<p>Select projects that challenge you yet are achievable within a realistic timeline. A mix of complex and straightforward projects shows versatility. Projects like a Data Dashboard or IoT Data Processing Service highlight your ability to work with data-centric applications.</p>
<p>Each project is a chance to display your technical skills and innovative approach. Tackling challenges such as developing secure authentication systems or engaging user interfaces can significantly showcase your development capabilities.</p>
<h3 id="heading-how-to-create-a-python-back-end-portfolio">How to Create a Python Back-end Portfolio</h3>
<p>In Python back-end development, crafting a personal portfolio is crucial. It's more than just a display of your skills – it’s a showcase of your practical expertise and your ability to solve real-world problems. The projects you choose to include in your portfolio provide tangible proof of your capabilities to future employers or clients. It’s important to remember that you don’t have to excel in every possible project.</p>
<p>When deciding on the right projects to undertake, align them with your career goals and personal interests. Your portfolio should accurately reflect your professional aspirations in Python back-end development.</p>
<p>Start by identifying the skills you want to highlight. Whether it’s database management, API development, or system integration, select projects that emphasize these abilities. For example, if your aim is to work in data-centric roles, projects like a Data Dashboard or an IoT Data Processing Service would be particularly relevant.</p>
<p>Next, consider the complexity and scope of each project. It’s essential to find a balance – challenging yourself is good, but you also want to complete projects in a reasonable time frame. A well-rounded portfolio that includes a mix of both intricate and simpler, well-executed projects can be more impressive than one filled with unfinished, overly ambitious projects.</p>
<p>Additionally, choose projects that genuinely interest you. Your enthusiasm for a project can lead to more dedication and a higher quality final product. If the idea of creating a Real-time Chat Application excites you, pursue it. Your passion can be a driving force in your learning and can result in more creative and engaging projects.</p>
<p>Keep in mind, your portfolio is an evolving element of your professional growth. Begin with one or two projects that align with your professional objectives and personal interests, and expand your portfolio over time. Each project you undertake is a step forward in your Python back-end development career, enhancing your expertise and confidence.</p>
<p>So, take the initiative, select a project, and begin coding. Every line of code you write contributes not just to an application, but to your future in the dynamic field of Python back-end development.</p>
<h4 id="heading-1-blog-platform">1. Blog Platform</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Implementing user authentication and designing relational databases not only strengthens your foundation in security and data management but also demonstrates your capability to handle core web functionalities.</li>
<li><strong>Technical Highlights</strong>: Develop user registration and login systems using Django or Flask, highlighting your expertise in handling user data securely. Designing a database schema to manage posts and comments will showcase your proficiency with Django’s ORM or Flask with SQL extensions.</li>
<li><strong>Additional Features</strong>: Enhance your platform with post categorization, robust search functionality, and rich text editing to demonstrate your attention to detail and user experience.</li>
</ul>
<h4 id="heading-2-e-commerce-website">2. E-commerce Website</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Developing an e-commerce site tests your ability to design complex databases and create APIs, crucial for handling dynamic user interactions and integrating external services.</li>
<li><strong>Technical Highlights</strong>: Build a structured product catalog and order management system, integrating RESTful services for seamless product interactions. Adding payment processing using APIs like Stripe or PayPal illustrates your adeptness in third-party integrations.</li>
<li><strong>Additional Features</strong>: Implement inventory management and user reviews, incorporating recommendation algorithms to display your skills in enhancing user engagement.</li>
</ul>
<h4 id="heading-3-social-media-api">3. Social Media API</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Building a RESTful API for social media sharpens your skills in data modeling and secure authentication, essential for modern web applications.</li>
<li><strong>Technical Highlights</strong>: Develop robust APIs for managing user profiles and interactions. Implement OAuth for secure user authentication, and optimize data queries for efficient performance.</li>
<li><strong>Additional Features</strong>: Incorporate real-time notifications, an intelligent news feed algorithm, and media upload support to elevate your application's user experience.</li>
</ul>
<h4 id="heading-4-task-management-application">4. Task Management Application</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Creating a task management tool focuses on your ability to implement CRUD operations and manage user sessions, integrating these with a front-end framework for a comprehensive application development experience.</li>
<li><strong>Technical Highlights</strong>: Develop functionalities for task creation, updates, and organization. Securely manage user sessions, showcasing your ability to handle sensitive data. Integrate with front-end frameworks like React or Angular to demonstrate your full-stack development capabilities.</li>
<li><strong>Additional Features</strong>: Add task prioritization, set deadlines, and reminders to demonstrate your proficiency in enhancing user productivity.</li>
</ul>
<h4 id="heading-5-real-time-chat-application">5. Real-time Chat Application</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: This project tests your skills in asynchronous programming and handling real-time data, crucial for applications requiring immediate data reflection and interaction.</li>
<li><strong>Technical Highlights</strong>: Implement WebSocket for real-time, bidirectional communication. Efficiently manage concurrent user connections and ensure seamless message synchronization across clients.</li>
<li><strong>Additional Features</strong>: Introduce chat rooms, file sharing, and user status indicators to demonstrate your ability to create feature-rich, interactive applications.</li>
</ul>
<h4 id="heading-6-data-dashboard">6. Data Dashboard</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Building a data dashboard allows you to showcase your expertise in data fetching, processing, and visualization — key skills for handling and presenting data insights.</li>
<li><strong>Technical Highlights</strong>: Utilize Python libraries like Pandas for data manipulation and Matplotlib or Plotly for creating interactive visualizations. Efficiently fetch and process data from various sources.</li>
<li><strong>Additional Features</strong>: Implement customizable widgets and user-specific views, demonstrating your ability to create tailored user experiences.</li>
</ul>
<h4 id="heading-7-machine-learning-model-deployment">7. Machine Learning Model Deployment</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Deploying a machine learning model as a web service shows your readiness to delve into the world of AI, highlighting your skills in integrating complex algorithms into practical applications.</li>
<li><strong>Technical Highlights</strong>: Deploy a pre-trained model and develop APIs for user interaction. Focus on scalability and performance, ensuring your application can handle varying loads.</li>
<li><strong>Additional Features</strong>: Add features for model retraining and incorporate user feedback loops, showcasing your commitment to continuous improvement and user-centric design.</li>
</ul>
<h4 id="heading-8-iot-data-processing-service">8. IoT Data Processing Service</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: This service demonstrates your ability to handle streaming data and process information from IoT devices, a rapidly growing field in technology.</li>
<li><strong>Technical Highlights</strong>: Develop a system to collect, process, and store IoT device data, utilizing cloud platforms like AWS or Azure for scalability and reliability.</li>
<li><strong>Additional Features</strong>: Include real-time data visualization, device management features, and anomaly detection algorithms, showcasing your innovative approach to data handling.</li>
</ul>
<h4 id="heading-9-content-management-system-cms">9. Content Management System (CMS)</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Creating a CMS from scratch tests your abilities in database schema design, user authentication, and implementing role-based access controls — key elements in creating secure and scalable web applications.</li>
<li><strong>Technical Highlights</strong>: Develop a flexible content system with diverse user roles and permissions. Focus on streamlined content creation, editing, and publishing workflows.</li>
<li><strong>Additional Features</strong>: Incorporate plugin or theme support, add SEO tools, and implement content versioning to demonstrate your foresight in creating a versatile and user-friendly system.</li>
</ul>
<h4 id="heading-10-online-reservation-system">10. Online Reservation System</h4>
<ul>
<li><strong>Skills Demonstrated</strong>: Developing an online reservation system showcases your ability to integrate external APIs and handle complex queries, essential for creating applications that interact with various external services.</li>
<li><strong>Technical Highlights</strong>: Build a comprehensive booking and reservation management system. Seamlessly integrate with additional services like payment processing and mapping.</li>
<li><strong>Additional Features</strong>: Implement user recommendation algorithms, reservation reminders, and promotional offers, highlighting your dedication to creating an engaging and user-friendly experience.</li>
</ul>
<p>The significance of a well-developed portfolio in Python back-end development is immense. It not only showcases your technical skills but also demonstrates your problem-solving capabilities to potential employers or clients. However, remember that quality trumps quantity. It's more effective to focus on a few projects that align with your career goals and highlight your core competencies.</p>
<p>Projects like a Blog Platform or an E-commerce Website are ideal for demonstrating a range of abilities in Python back-end development. Each project should reflect professional standards, including well-written code and comprehensive documentation. As you grow in your career, keep your portfolio updated with your latest work, ensuring it evolves with industry trends and best practices.</p>
<p>In essence, carefully select projects that showcase your strengths, and let your portfolio narratively represent your professional growth in Python back-end development. It's your key to unlocking new opportunities in this dynamic field.</p>
<h3 id="heading-back-end-python-interview-questions">Back-end Python Interview Questions</h3>
<p>Preparing for a back-end Python developer interview requires a solid grasp of both the technical and soft skills essential for the role. This chapter is designed to arm you with a comprehensive set of questions that cover a wide range of topics, from general programming knowledge and specific Python skills to problem-solving abilities and understanding of back-end technologies. </p>
<p>Whether you're a seasoned developer or new to back-end development, these questions will help you assess your preparedness and identify areas for improvement.</p>
<h4 id="heading-general-and-behavioral-questions">General and Behavioral Questions</h4>
<ol>
<li>Can you describe your experience with back-end development?</li>
<li>How do you stay updated with the latest back-end technologies and trends?</li>
<li>Describe a challenging back-end project you worked on.</li>
<li>How do you approach debugging a complex problem?</li>
<li>Can you discuss a time you improved the performance of a web application?</li>
<li>How do you ensure the security of your web applications?</li>
<li>Describe your experience with team collaboration in development projects.</li>
<li>What's your process for testing and quality assurance?</li>
<li>How do you handle tight deadlines and pressure?</li>
<li>What motivates you in back-end development?</li>
</ol>
<h4 id="heading-technical-skills-and-coding-questions">Technical Skills and Coding Questions</h4>
<ol>
<li>What languages are you most proficient in for back-end development?</li>
<li>Can you explain RESTful API design?</li>
<li>What are the differences between SQL and NoSQL databases? When would you use each?</li>
<li>How do you manage database transactions and prevent data inconsistencies?</li>
<li>What are some common HTTP methods, and how are they used?</li>
<li>Explain the concept of MVC architecture.</li>
<li>How do you optimize database queries?</li>
<li>What is containerization, and how does it benefit development?</li>
<li>Describe the process of API authentication and authorization.</li>
<li>How do you manage cross-origin resource sharing (CORS) in web applications?</li>
</ol>
<h4 id="heading-frameworks-and-technologies">Frameworks and Technologies</h4>
<ol>
<li>What experience do you have with frameworks like Django, Flask, or Express.js?</li>
<li>How do you handle session management in web applications?</li>
<li>Can you explain the concept of middleware in web development?</li>
<li>What is your experience with cloud services like AWS, Azure, or Google Cloud?</li>
<li>How have you used caching mechanisms to improve application performance?</li>
<li>What are some challenges you have faced using ORM tools?</li>
<li>Describe your experience with microservices architecture.</li>
<li>How do you ensure the scalability of your web applications?</li>
<li>What tools do you use for version control?</li>
<li>How do you approach mobile backend development differently from web backend?</li>
</ol>
<h4 id="heading-problem-solving-and-algorithm-questions">Problem-Solving and Algorithm Questions</h4>
<ol>
<li>How would you design a system for handling high traffic loads?</li>
<li>Describe how you would implement a rate-limiting feature.</li>
<li>How would you handle data synchronization across different services?</li>
<li>Describe your approach to implementing a full-text search in a database.</li>
<li>Can you explain the concept of load balancing and how it works?</li>
<li>How would you design a notification system for a high-traffic application?</li>
<li>Discuss how you would secure sensitive data in transit and at rest.</li>
<li>How do you approach error handling and logging in back-end applications?</li>
<li>Describe a time when you had to refactor code for better efficiency.</li>
<li>How do you handle database schema migrations?</li>
</ol>
<h4 id="heading-specific-technologiesconcepts-questions">Specific Technologies/Concepts Questions</h4>
<ol>
<li>Explain the concept of stateless architecture.</li>
<li>What is the difference between SOAP and REST APIs?</li>
<li>How do you implement a WebSocket, and what are its advantages?</li>
<li>What are some best practices for API versioning?</li>
<li>How do you handle file uploads in your web applications?</li>
<li>Describe the process of integrating third-party services via APIs.</li>
<li>What is OAuth, and how do you implement it?</li>
<li>How do you handle concurrency issues in a database?</li>
<li>Explain the role of a reverse proxy in web applications.</li>
<li>What is the difference between horizontal and vertical scaling?</li>
</ol>
<h4 id="heading-scenario-based-questions">Scenario-Based Questions</h4>
<ol>
<li>How would you optimize an application with slow response times?</li>
<li>Describe how you would scale a database for a growing application.</li>
<li>How would you troubleshoot a memory leak in an application?</li>
<li>Imagine a scenario where users report frequent timeouts. How would you investigate?</li>
<li>Describe how you would handle a security breach in a web application.</li>
<li>How would you manage data consistency across distributed systems?</li>
<li>If a service is failing intermittently, how would you go about diagnosing it?</li>
<li>Explain how you would design a back-end for an e-commerce site.</li>
<li>Describe the steps you would take to migrate a monolithic application to microservices.</li>
<li>How would you design a back-end system for real-time data processing?</li>
</ol>
<h4 id="heading-advanced-conceptual-questions">Advanced Conceptual Questions</h4>
<ol>
<li>What are idempotent operations, and why are they important?</li>
<li>Can you explain the concept of eventual consistency?</li>
<li>Describe the trade-offs of a monolithic vs. microservices architecture.</li>
<li>What is the CAP theorem, and how does it apply to database systems?</li>
<li>How do you approach dependency injection in back-end applications?</li>
<li>Explain the concept of Domain-Driven Design (DDD) in back-end development.</li>
<li>What are design patterns, and can you give examples of how you've used them?</li>
<li>How does event-driven architecture work in back-end systems?</li>
<li>Explain the role of service discovery in microservices.</li>
<li>What are some strategies for dealing with database replication lag?</li>
</ol>
<h4 id="heading-performance-and-optimization-questions">Performance and Optimization Questions</h4>
<ol>
<li>How do you monitor the performance of your applications?</li>
<li>Can you discuss strategies for reducing server load?</li>
<li>What are some ways to handle high-volume data processing efficiently?</li>
<li>How do you approach optimizing application boot time?</li>
<li>What tools do you use for performance profiling?</li>
<li>Discuss how you would reduce the response time of a database query.</li>
<li>What strategies can be used to reduce the size of a web application's payload?</li>
<li>How do you optimize resource utilization in cloud services?</li>
<li>What are some common performance bottlenecks in web applications, and how do you address them?</li>
<li>How do you ensure efficient memory management in your applications?</li>
</ol>
<h4 id="heading-collaboration-and-workflow-questions">Collaboration and Workflow Questions</h4>
<ol>
<li>How do you approach code reviews?</li>
<li>What's your experience working in Agile development environments?</li>
<li>How do you handle merge conflicts in a version control system?</li>
<li>Describe your experience with Continuous Integration/Continuous Deployment (CI/CD).</li>
<li>How do you prioritize tasks in a fast-paced development environment?</li>
<li>Describe a time you had to collaborate with front-end developers to solve a problem.</li>
<li>How do you document your code and API for other developers?</li>
<li>What strategies do you use to ensure clear communication in a remote team?</li>
<li>How do you stay aligned with product management and other stakeholders?</li>
<li>Describe your approach to mentoring or onboarding new team members.</li>
</ol>
<h4 id="heading-personal-growth-and-learning-questions">Personal Growth and Learning Questions</h4>
<ol>
<li>How do you keep your programming skills sharp?</li>
<li>What's the last programming book you read, or tech talk you watched?</li>
<li>How do you approach learning a new programming language or framework?</li>
<li>Can you share an example of a recent technical challenge and how you solved it?</li>
<li>What areas of back-end development are you looking to improve in?</li>
<li>Describe a technical topic you're passionate about.</li>
<li>How do you balance work with personal development and learning?</li>
<li>What's your experience with open-source projects?</li>
<li>How do you handle feedback and criticism on your code?</li>
<li>What goals do you have for your future in back-end development?</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As we wrap up this comprehensive exploration of Python back-end development, it's clear that the journey you're embarking on is both challenging and rewarding. </p>
<p>Python, with its simplicity, versatility, and powerful libraries, stands as a cornerstone for building robust back-end systems. This guide aimed to equip you with the foundational knowledge, best practices, and practical insights necessary to thrive as a Python back-end developer.</p>
<h3 id="heading-key-takeaways">Key Takeaways:</h3>
<ul>
<li><strong>Python's Role:</strong> You've learned that Python is not just versatile but pivotal in back-end development. Its frameworks, like Django, Flask, and FastAPI, enable you to build efficient, scalable applications.</li>
<li><strong>Database Mastery:</strong> Understanding the nuances of SQL and NoSQL databases enhances your ability to manage data effectively, ensuring performance and scalability.</li>
<li><strong>Security First:</strong> Emphasizing security practices, from authentication to encryption, is critical. This ensures the integrity and confidentiality of data, building trust and reliability.</li>
<li><strong>Practical Portfolio:</strong> Developing a portfolio with diverse projects demonstrates your skills and problem-solving capabilities, making you stand out in the job market.</li>
<li><strong>Interview Preparedness:</strong> The detailed set of interview questions prepares you to articulate your knowledge and experience confidently, showcasing your readiness for back-end roles.</li>
</ul>
<h3 id="heading-moving-forward">Moving Forward:</h3>
<ul>
<li><strong>Continuous Learning:</strong> The field of back-end development is ever-evolving. Stay curious, keep learning, and embrace the changes in technologies and methodologies.</li>
<li><strong>Community Engagement:</strong> Join forums, contribute to open-source projects, and network with professionals. The insights and connections you gain are invaluable for your growth and career advancement.</li>
<li><strong>Practical Application:</strong> Apply what you've learned in real-world scenarios. Whether through personal projects, freelancing, or in your job, hands-on experience solidifies your skills and opens up new opportunities.</li>
<li><strong>Mentorship and Sharing:</strong> As you grow, seek mentorship from experienced developers. Similarly, share your knowledge with those who are starting their journey. Teaching is a powerful way to reinforce your own learning and contribute to the community.</li>
</ul>
<p>Embarking on your career as a Python back-end developer is a journey of continuous growth, innovation, and discovery. With the skills and knowledge you've acquired, you're well-equipped to tackle the challenges and opportunities that lie ahead. Embrace the journey with confidence, passion, and a willingness to explore new horizons in the dynamic world of Python back-end development.</p>
<h3 id="heading-resources"><strong>Resources</strong></h3>
<p>Kickstart your journey in technology with our specialized program that dives into Artificial Intelligence (AI) and machine learning. This initiative is crafted to build your programming expertise, supplemented with dedicated mentorship and career guidance to pave your way in the tech industry.</p>
<p>To enrich your learning experience, here's a helpful selection of targeted resources:</p>
<ul>
<li><a target="_blank" href="https://downloads.tatevaslanyan.com/six-figure-data-science-ebook">How to Enter Gen AI in 2024:</a> This guide breaks down the essentials of emerging AI technologies and prepares you for future trends.</li>
<li><a target="_blank" href="https://join.lunartech.ai/software-engineering-internship">Land Your Software Engineering Internship:</a> This resource provides step-by-step instructions for finding and landing a valuable internship in software engineering, giving you a competitive edge.</li>
<li><a target="_blank" href="https://join.lunartech.ai/machine-learning-fundamentals--3f64f">Machine Learning Fundamentals eBook:</a> Begin your exploration of machine learning with this eBook, which provides a concise overview of its core principles and techniques.</li>
</ul>
<p>For access to these resources and detailed information about our program, visit LunarTech's website. Embark on your tech career path with the right tools and support from LunarTech.</p>
<h3 id="heading-connect-with-me"><strong>Connect with Me:</strong></h3>
<ul>
<li><a target="_blank" href="https://ca.linkedin.com/in/vahe-aslanyan">Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI</a></li>
<li><a target="_blank" href="https://vaheaslanyan.com/">Visit my Personal Website</a></li>
<li>Subscribe to my <a target="_blank" href="https://tatevaslanyan.substack.com/">The Data Science and AI Newsletter</a></li>
</ul>
<h3 id="heading-about-the-author"><strong>About the Author</strong></h3>
<p>I'm Vahe Aslanyan, specializing in the world of computer science, data science, and artificial intelligence. Explore my work at <a target="_blank" href="https://www.vaheaslanyan.com/">vaheaslanyan.com</a>. My expertise encompasses robust full-stack development and the strategic enhancement of AI products, with a focus on inventive problem-solving.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.vaheaslanyan.com/">https://www.vaheaslanyan.com/</a></div>
<p>My experience includes spearheading the launch of a prestigious data science bootcamp, an endeavor that put me at the forefront of industry innovation. I've consistently aimed to revolutionize technical education, striving to set a new, universal standard.</p>
<p>As we close this handbook, I extend my sincere thanks for your focused engagement. Imparting my professional insights through this book has been a journey of professional reflection. Your participation has been invaluable. I anticipate these shared experiences will significantly contribute to your growth in the dynamic field of technology.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Communication Design Patterns for Backend Development ]]>
                </title>
                <description>
                    <![CDATA[ By Chinwendu Enyinna When you’re building the backend of an application, you’ve got to figure out how all the different components are going to talk to each other.  It’s like setting up a communication network for your app’s brain, and the way you do... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/communication-design-patterns-for-backend-development/</link>
                <guid isPermaLink="false">66d45e01bc9760a197a10370</guid>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 12 Sep 2023 16:25:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/comm-design-patterns.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Chinwendu Enyinna</p>
<p>When you’re building the backend of an application, you’ve got to figure out how all the different components are going to talk to each other. </p>
<p>It’s like setting up a communication network for your app’s brain, and the way you do it can seriously impact how well your app performs.</p>
<p>But here’s the fun part: there’s no one-size-fits-all answer. The communication pattern you choose depends on what your application needs to do. </p>
<p>So, in this tutorial, we’re going to take a look at five different ways backend systems like to chat it up. We’ll explore what they’re good at and when you should invite them to the conversation. Let’s dive right in!</p>
<h2 id="heading-what-is-a-design-pattern">What is a Design Pattern?</h2>
<p>Before we get into all the cool patterns, let’s talk about what a design pattern is, shall we?</p>
<p><strong>Design patterns</strong> are nifty, tried-and-true reusable solutions to common problems encountered during software design and development. You can call them the cheat codes of software design and development. </p>
<p>They can help provide a structured approach to solving recurring challenges, offering a set of guidelines and best practices that can be adapted for various scenarios.</p>
<p>Now that we’ve got that down, let’s explore five of these emerging design patterns used for backend communication.</p>
<h2 id="heading-request-response-pattern">Request-Response Pattern</h2>
<p>The request-response pattern is a fundamental building block for how the front-end and back-end of web applications chat with each other. This pattern is like a conversation between the client (say your browser) and the server, where they take turns speaking. Imagine it as a “ping-pong” of data.</p>
<p>Here's a diagram illustrating what that looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/Untitled-2023-08-13-1619.png" alt="Image" width="600" height="400" loading="lazy">
<em>request/response communication model</em></p>
<p><img src="https://cdn-images-1.medium.com/max/800/1*SQDgiDS9Ouqi7tksE9744w.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-does-the-request-response-pattern-work">How does the Request-Response pattern work?</h3>
<p>This pattern is all about synchronization. The client sends a request to the server, kind of like raising your hand to ask a question in class. Then it patiently waits for the server to respond before it can move on. </p>
<p>It’s like a polite conversation — one speaks, the other listens, and then they swap roles.</p>
<p>You’ve probably heard of RESTful APIs, right? Well, they’re a prime example of the request-response model in action. </p>
<p>When your app needs some data or wants to do something on the server, it crafts an HTTP request — say GET, POST, PUT, or DELETE (like asking nicely for a page), and sends it to specific endpoints (URLs) on the server. The server then processes your request and replies with the data you need or performs the requested action. </p>
<p>It’s like ordering your favorite dish from a menu — you ask, and the kitchen (server) cooks it up for you.</p>
<p>Interestingly, there’s more than one way to have this conversation. Besides REST, there’s GraphQL, an alternative that lets you ask for exactly the data you want. It’s like customizing your order at a restaurant — you get to pick and choose your ingredients.</p>
<p>It’s important to note that this pattern isn’t just limited to web applications. You’ll spot it in Remote Procedure Calls (RPCs), database queries (with the server being the client and the database, the server), and network protocols (HTTP, SMTP, FTP) to name a few. It’s like the language of communication for the web.</p>
<h3 id="heading-benefits-of-the-request-response-pattern">Benefits of the Request-Response pattern</h3>
<p><strong>Ease of Implementation and Simplicity:</strong> The way communication flows in this model is pretty straightforward, making it a go-to choice for many developers, especially when they’re building apps with basic interaction needs.</p>
<p><strong>Flexibility and Adaptability</strong> (One Size Fits Many): The request-response pattern seamlessly fits into a wide range of contexts. You can use it for making API calls, rendering web pages on the server, fetching data from databases, and more.</p>
<p><strong>Scalability:</strong> Each request from the client is handled individually, so the server can easily manage multiple requests at once. This is highly beneficial for high-traffic websites, APIs that get tons of calls, or cloud-based services.</p>
<p><strong>Reliability:</strong> Since the server always sends back a response, the client can be sure its request is received and processed. This helps maintain data consistency and ensures that actions have been executed as intended even during high-traffic scenarios.</p>
<p><strong>Ease of Debugging:</strong> If something goes wrong, the server kindly sends an error message with a status code stating what happened. This makes error handling easy.</p>
<h3 id="heading-limitations-of-the-request-response-pattern">Limitations of the Request-Response Pattern</h3>
<p><strong>Latency Problem:</strong> Because it’s a back-and-forth conversation, there’s often a waiting period. This amounts to idle periods and amplifies latency, especially when the request requires the server to perform time-consuming computing tasks.</p>
<p><strong>Data Inconsistency in Case of Failures:</strong> If a failure occurs after the server has processed the request but before the response is delivered to the client, data inconsistency may result.</p>
<p><strong>Complexity in Real-Time Communication:</strong> For applications that need lightning-fast real-time communication (like live streaming, gaming, or chat apps), this pattern can introduce delays and is therefore unsuitable for these use-cases.</p>
<p><strong>Inefficiency in Broadcasting:</strong> In scenarios where you need to send the same data to multiple clients at once (broadcast), this pattern can be a bit inefficient. It’s like mailing individual letters instead of sending one group message.</p>
<p>Here’s a code example that shows the request-response pattern using Nodejs.</p>
<p>First, we have the <code>server.js</code> file. Here we’ve set up the server to listen for incoming requests from the client.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
 res.statusCode = <span class="hljs-number">200</span>;
 res.setHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"text/plain"</span>);

 <span class="hljs-comment">//check request method and receive data from client</span>
 <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">"POST"</span>) {
  <span class="hljs-keyword">let</span> incomingMessage = <span class="hljs-string">""</span>;
  req.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> {
   incomingMessage += chunk;
  });

  <span class="hljs-comment">//write back message received from the client on the console</span>
  req.on(<span class="hljs-string">"end"</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Message from client: <span class="hljs-subst">${incomingMessage}</span>`</span>);
   res.end(<span class="hljs-string">`Hello client, message received!`</span>);
  });
 } <span class="hljs-keyword">else</span> {
  res.end(<span class="hljs-string">"Hey there,  Client!\n"</span>);
 }
});

<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">3030</span>;
server.listen(PORT, <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(
  <span class="hljs-string">`Server is listening for incoming request from client on port:<span class="hljs-subst">${PORT}</span>`</span>
 );
});
</code></pre>
<p>And here's the <code>client.js file</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

<span class="hljs-keyword">const</span> options = {
 <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
 <span class="hljs-attr">hostname</span>: <span class="hljs-string">"localhost"</span>,
 <span class="hljs-attr">port</span>: <span class="hljs-number">3030</span>,
 <span class="hljs-attr">path</span>: <span class="hljs-string">"/"</span>,
};

<span class="hljs-comment">//message to server</span>
<span class="hljs-keyword">let</span> messageToServer = <span class="hljs-string">"Hey there, server!"</span>;

<span class="hljs-comment">//send a http request to the server</span>
<span class="hljs-keyword">const</span> req = http.request(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
 <span class="hljs-keyword">let</span> incomingData = <span class="hljs-string">""</span>;

 res.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> {
  incomingData += chunk;
 });

 res.on(<span class="hljs-string">"end"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Response from the server: <span class="hljs-subst">${incomingData}</span>`</span>);
 });
});

req.on(<span class="hljs-string">"error"</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error message: <span class="hljs-subst">${error.message}</span>`</span>);
});

<span class="hljs-comment">//send message to the server</span>
req.write(messageToServer);

<span class="hljs-comment">//end your request</span>
req.end();
</code></pre>
<p>Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--173-.png" alt="Image" width="600" height="400" loading="lazy">
<em>code output on the terminal</em></p>
<h2 id="heading-the-publishsubscribe-pattern">The Publish/Subscribe Pattern</h2>
<p>Publish/Subscribe is another communication design pattern you may see on the backend. It is used in distributed systems for asynchronous communication between several (usually decoupled) components. It’s perfect for when you’ve got a bunch of components that need to work together but want to keep their distance.</p>
<p>Here's a diagram showing how it works:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/Untitled-2023-08-13-1619-9.png" alt="Image" width="600" height="400" loading="lazy">
<em>Pub/Sub communication model</em></p>
<h3 id="heading-how-does-the-publishsubscribe-pattern-work">How does the Publish/Subscribe pattern work?</h3>
<p>This pattern involves the use of message queues (often called message brokers) which serve as intermediaries between the publishers and subscribers. These message brokers group messages into something called channels (or topics).</p>
<p>Publishers are the components that create and send messages while subscribers are the components that receive and consume the messages.</p>
<p>The publishers simply toss messages (or events) into specific channels/topics within the message broker. These channels act as the distribution point for the messages. The subscribers then indicate interest by subscribing to those channels within the message broker and whenever a message or event is published to that channel, they receive a copy.</p>
<p>Message queuing tools like Apache Kafka and MQTT use the publish/subscribe communication pattern under the hood.</p>
<h3 id="heading-benefits-of-the-publishsubscribe-pattern">Benefits of the Publish/Subscribe pattern</h3>
<p><strong>Asynchronous Communication:</strong> Unlike the request-response model, pub/sub is designed to be asynchronous by nature. This makes it ideal for building real-time applications with reduced latency bottlenecks.</p>
<p><strong>Loose Coupling of Components:</strong> The components in a publish/subscribe model are loosely coupled. This means that they are not tied together and can freely interact by triggering and responding to events.</p>
<p><strong>Highly Scalable:</strong> There is no limit to the number of subscribers a publisher can publish events to. Also, there’s no limit to the number of publishers subscribers can subscribe to.</p>
<p><strong>Independent of Language and Protocol:</strong> The Pub/Sub model can be easily integrated into any tech stack because it is language-agnostic. Also, it often supports a wide range of environments and platforms making it cross-platform compatible.</p>
<p><strong>Load Balancing:</strong> In cases where multiple subscribers subscribe to a particular event, the pub/sub model can distribute the events evenly among the subscribers, providing load-balancing capabilities out of the box.</p>
<h3 id="heading-limitations-of-the-publishsubscribe-pattern">Limitations of the Publish/Subscribe pattern</h3>
<p><strong>Complexity in Implementation:</strong> Setting up a Pub/Sub system can be more complex than simpler communication models like the request-response pattern. You need to configure and manage message brokers, channels, and subscriptions, which can add overhead to your system.</p>
<p><strong>Message Duplication:</strong> Depending on the configuration and network issues, messages can be duplicated. Subscribers might receive the same message more than once, which can lead to redundancy and extra processing.</p>
<p><strong>Scalability Challenges:</strong> While Pub/Sub is highly scalable, managing extremely high volumes of messages and subscribers can become complex. You might need to consider how to distribute messages efficiently and handle massive numbers of subscribers.</p>
<p><strong>Complex Error Handling:</strong> Dealing with errors in a Pub/Sub system can be challenging. Handling situations like message delivery failures or subscriber errors requires careful consideration and design.</p>
<h3 id="heading-when-should-you-use-it">When should you use it?</h3>
<ul>
<li>In building features that require real-time and low latency responsiveness for the end-users, for example live chat or gaming applications for multiple players.</li>
<li>In event notification systems</li>
<li>In building distributed systems that rely on logging and caching</li>
</ul>
<p>Here’s a code snippet showing a simple pub/sub implementation using the npm package <strong><code>pubsub-js</code>.</strong></p>
<p>Here are the contents of the <code>pubsub.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> PubSub = <span class="hljs-built_in">require</span>(<span class="hljs-string">"pubsub-js"</span>);

<span class="hljs-comment">/*
create  a topic of choice.
Any subscriber that subscribes to this topic
receives the published messages
*/</span>
<span class="hljs-keyword">const</span> TOPIC = <span class="hljs-string">"chat"</span>;

<span class="hljs-comment">//a function to publish a messgae to subscribers</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">publishMessageToSubscribers</span>(<span class="hljs-params">message</span>) </span>{
 PubSub.publish(TOPIC, message);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Message Published: <span class="hljs-subst">${message}</span>`</span>);
}

<span class="hljs-keyword">let</span> subscriber1 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg, data</span>) </span>{
 <span class="hljs-built_in">console</span>.log(msg, data);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"subscriber1 received: "</span>, data);
};

<span class="hljs-keyword">let</span> subscriber2 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg, data</span>) </span>{
 <span class="hljs-built_in">console</span>.log(msg, data);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"subscriber2 received: "</span>, data);
};

<span class="hljs-comment">// Subscriber1 subscribes to the topic</span>
PubSub.subscribe(TOPIC, subscriber1);

<span class="hljs-comment">//subscriber2 subscribes to topic</span>
PubSub.subscribe(TOPIC, subscriber2);

publishMessageToSubscribers(<span class="hljs-string">"Hello subscriber!"</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Subscriber 1 is listening...."</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Subscriber 2 is listening...."</span>);
</code></pre>
<p>Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--180-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-short-polling-pattern">The Short Polling Pattern</h2>
<p>Short polling is another communication pattern that facilitates data exchange between client and server. It uses the <strong>pull-based</strong> communication mechanism (which is basically the client pulling data from the backend) to continuously poll the server for new updates.</p>
<h3 id="heading-how-does-short-polling-work">How does Short Polling work?</h3>
<p>Imagine you’re waiting for a message from a friend, and you don’t want to miss it. What do you do? You keep asking, “Got a message for me yet?”</p>
<p>So, the client makes a request to the server at regular (fixed) intervals (say every x unit of time) to check for new data or updates. The server sends back a response and if there’s new available data or an update, the server includes the data in the response.</p>
<p>Here’s what the client-server communication would look like:</p>
<ul>
<li>Client: “Hey, server, any new messages?”</li>
<li>Server: “Nah, nothing yet.”</li>
<li>Client: “Alright, I’ll check back later.”</li>
<li>[Some time passes…]</li>
<li>Client: “Hey, server, any new messages?”</li>
<li>Server: “Bingo! Here they are!”</li>
</ul>
<p>Although polling has some similarities with the request-response model we discussed earlier, a key difference between them is <strong>timing</strong>. </p>
<p>While polling occurs at regular, predefined intervals regardless of whether updates are available, the request-response model allows clients to request data or actions on-demand when needed, reducing unnecessary communication.</p>
<h3 id="heading-benefits-of-polling">Benefits of Polling</h3>
<p><strong>Simplicity:</strong> Polling is easy to understand and implement and it’s completely stateless between the client and server. This makes it perfect for scenarios where the complexities need to be minimized.</p>
<p><strong>Compatibility:</strong> It can be used with a wide range of technologies and protocols which makes it highly compatible with a number of platforms and environments.</p>
<p>Some example use cases of polling pattern includes simple dashboards, weather apps that require periodic updates, resource monitoring, or in cases where you’re considering cross-platform compatibility.</p>
<h3 id="heading-limitations-of-polling">Limitations of Polling</h3>
<p><strong>Latency:</strong> Polling introduces latency, as clients must wait for predefined intervals before receiving updates. This can lead to delays in accessing real-time data or receiving notifications.</p>
<p><strong>Inefficiency:</strong> Constantly polling the server for updates can be inefficient and can result in unnecessary network and server overhead.</p>
<p><strong>Scaling:</strong> Handling a large number of simultaneous clients using polling can be resource-intensive for the server. It may require significant server resources to manage numerous concurrent polling requests.</p>
<p>Here's a code snippet to illustrate short polling. Here, the client sends a periodic request(polls ) to the server to check for upload progress.</p>
<p>The <code>app.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">//create a dictionary to store the upload progress</span>
<span class="hljs-keyword">const</span> uploadStatus = {};

<span class="hljs-comment">//simulate upload of file</span>
app.post(<span class="hljs-string">"/upload"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
 <span class="hljs-comment">//create a unique request id for incoming request</span>
 <span class="hljs-keyword">const</span> requestId = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">1000000</span>);
 uploadStatus[requestId] = <span class="hljs-number">0</span>;

 simulateUploadProgress(requestId);

 res.json({ requestId });
});

<span class="hljs-comment">//endpoint to check upload progress</span>
app.get(<span class="hljs-string">"/status/:requestId"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
 <span class="hljs-keyword">const</span> requestId = <span class="hljs-built_in">parseInt</span>(req.params.requestId);

 <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">isNaN</span>(requestId) &amp;&amp; uploadStatus[requestId] !== <span class="hljs-literal">undefined</span>) {
  <span class="hljs-keyword">if</span> (uploadStatus[requestId] === <span class="hljs-number">100</span>) {
   <span class="hljs-comment">//upload completed</span>
   res.json({ <span class="hljs-attr">progress</span>: <span class="hljs-number">100</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">"UPLOAD COMPLETED!"</span> });
  } <span class="hljs-keyword">else</span> {
   <span class="hljs-comment">// upload still in progress</span>
   res.json({ <span class="hljs-attr">progress</span>: uploadStatus[requestId] });
  }
 } <span class="hljs-keyword">else</span> {
  res.status(<span class="hljs-number">404</span>).json({ <span class="hljs-attr">error</span>: <span class="hljs-string">"Request ID not found"</span> });
 }
});

<span class="hljs-comment">//update upload progress by 10% every 5 secs</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">simulateUploadProgress</span>(<span class="hljs-params">requestId</span>) </span>{
 <span class="hljs-keyword">if</span> (uploadStatus[requestId] &lt; <span class="hljs-number">100</span>) {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
   uploadStatus[requestId] += <span class="hljs-number">10</span>;
   simulateUploadProgress(requestId);
  }, <span class="hljs-number">5000</span>);
 }
}
<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">4000</span>;

app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port <span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre>
<p>Here's the output in the terminal</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--189--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-the-long-polling-pattern">The Long Polling Pattern</h2>
<p>Long polling is like polling but uses a <strong>push-based</strong> communication mechanism. In long polling, instead of the client asking the server, “Any updates?” all the time, it says, “Let me know when something’s up.”</p>
<h3 id="heading-heres-how-long-polling-works">Here’s how Long Polling works:</h3>
<p>The client pings the server, just like in regular polling, but this time, the server doesn’t immediately answer. It holds the connection open, like keeping a phone line on hold. When there’s something to share, it responds. It’s like the server’s saying, “Hey, I’ll call you when I have news.”</p>
<p>It is used in web applications to achieve real-time or near-real-time updates between a client and a server.</p>
<h3 id="heading-benefits-of-the-long-polling-pattern">Benefits of the Long Polling Pattern</h3>
<p><strong>Low Latency:</strong> Long polling provides low latency when compared to traditional polling as data is immediately sent back to clients as soon as they are available.</p>
<p><strong>Real-Time Updates:</strong> With the long polling technique, applications can achieve real-time updates without the need for constantly polling the server.</p>
<h3 id="heading-limitations-of-the-long-polling-pattern">Limitations of the Long Polling Pattern</h3>
<p><strong>Resource Intensive:</strong> Long polling requires keeping many connections open. As a result, it can be resource-consuming on both the server and client side.</p>
<p><strong>Increased Latency:</strong> Although long polling helps cut down on frequent polling, it can still introduce latency when compared to other real-time communication protocols like Web Socket. Clients may experience delays between updates since they have to wait for the server to respond.</p>
<p><strong>Difficult to Scale:</strong> When dealing with a large number of concurrent clients, long polling can strain server resources. As more clients establish long-polling connections, the server may struggle to manage and respond to all these connections efficiently.</p>
<p>Typical use cases of long polling include real-time updates, event-driven applications, and event notification systems.</p>
<p>Here's a code snippet to illustrate the concept of long polling where the client waits for updates from the server.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-keyword">const</span> uploadStatus = {};

app.post(<span class="hljs-string">"/upload"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
 <span class="hljs-keyword">const</span> requestId = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">1000000</span>);
 uploadStatus[requestId] = <span class="hljs-number">0</span>;

 updateUploadProgress(requestId, uploadStatus[requestId]);

 res.json({ requestId });
});

app.get(<span class="hljs-string">"/status/:requestId"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
 <span class="hljs-keyword">const</span> requestId = <span class="hljs-built_in">parseInt</span>(req.params.requestId);

 <span class="hljs-comment">//simulate long polling (the server will not respond until done)</span>
 <span class="hljs-keyword">while</span> ((<span class="hljs-keyword">await</span> checkUploadComplete(requestId)) === <span class="hljs-literal">false</span>);
 res.end(<span class="hljs-string">"\n\n Upload status: completed "</span> + uploadStatus[requestId]);
});

<span class="hljs-comment">//update progress by 20% after every 5 seconds</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateUploadProgress</span>(<span class="hljs-params">requestId, progress</span>) </span>{
 uploadStatus[requestId] = progress;
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Updated progress to <span class="hljs-subst">${progress}</span>`</span>);
 <span class="hljs-keyword">if</span> (progress === <span class="hljs-number">100</span>) <span class="hljs-keyword">return</span>;
 <span class="hljs-built_in">this</span>.setTimeout(<span class="hljs-function">() =&gt;</span> updateUploadProgress(requestId, progress + <span class="hljs-number">20</span>), <span class="hljs-number">5000</span>);
}

<span class="hljs-comment">//check upload status</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkUploadComplete</span>(<span class="hljs-params">requestId</span>) </span>{
 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (uploadStatus[requestId] &lt; <span class="hljs-number">100</span>) {
   <span class="hljs-built_in">this</span>.setTimeout(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-literal">false</span>), <span class="hljs-number">1000</span>);
  } <span class="hljs-keyword">else</span> {
   resolve(<span class="hljs-literal">true</span>);
  }
 });
}
<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">4000</span>;

app.listen(PORT, <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port <span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre>
<p>And here's the output in the terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/Screenshot--188-.png" alt="Image" width="600" height="400" loading="lazy">
<em>code output</em></p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/QDvSPKZzf1s" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-the-push-pattern">The Push Pattern</h2>
<p>Push is a communication model that is used to deliver real-time updates to connected clients. </p>
<p>In this model, the client opens a connection to the server and awaits messages or updates from the server. Whenever there is a new update or message, the server immediately <strong>pushes</strong> that update to the client without the client explicitly requesting it — as long it is connected.</p>
<p>This model allows for bidirectional communication between the client and server. Web sockets, a popular protocol, uses the push model as its underlying data exchange method.</p>
<p>The Push model provides the most real-time or near real-time end-user experience when compared to other closely related paradigms such as polling and long polling.</p>
<p>To explain how the push pattern works, imagine a chat room with multiple connected users as an example. The client and server conversation will look like this:</p>
<ul>
<li>user1 (client): “Hello…”</li>
<li>Server: “Oh, user1 has a message!” <em>Instantly sends it to everyone else in the room.</em></li>
<li>User2 (client): <em>Gets the message from user1 without doing anything.</em></li>
<li>User3 (client): <em>Also receives the message from user1 — no need to refresh or ask for it.</em></li>
</ul>
<p>In the example above, the push pattern enables real-time communication such that whenever there’s a message from a client in the chat room, it pushes the message to all other connected clients in that room without them having to continuously poll or request updates.</p>
<p>Popular technologies that uses the push pattern are RabbitMQ and WebSocket.</p>
<h3 id="heading-benefits-of-push-pattern">Benefits of Push Pattern</h3>
<p><strong>Real-Time Updates:</strong> The push model allows clients to receive updates from the server as soon as they are available. This is key, especially in applications where real-time updates are crucial.</p>
<p><strong>Reduced Latency:</strong> Since the server pushes updates to the client as soon as they are available, it potentially reduces the latency.</p>
<p><strong>Efficiency:</strong> Because there is no need for continuous polling or frequent client requests, there is efficient use of network resources and reduced server load.</p>
<p>While the push model is widely adopted as the best fit for providing real-time updates, it does have its own disadvantages.</p>
<h3 id="heading-limitations-of-push-pattern">Limitations of Push Pattern</h3>
<p><strong>Scalability:</strong> It can become difficult to scale as the number of connected clients increases. At this point, it becomes resource-intensive, especially on the server side since the server needs to maintain open connections with multiple clients.</p>
<p><strong>Client support:</strong> Some clients might not be able to handle pushed messages as not all client platforms support push technologies. This may lead to compatibility issues and may need some sort of fallback mechanism for unsupported clients.</p>
<p>Some example use cases of the push pattern include chat and messaging apps, notification systems, IoT data streaming, and online gaming, to name a few.</p>
<p>Here’s a simple Node.js code example to illustrate the push pattern using Web Sockets. To run the code, you have to install the <code>ws</code> library using  <code>npm</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//create a server - this server will push updates to the clients at intervals</span>
<span class="hljs-keyword">const</span> WebSocket = <span class="hljs-built_in">require</span>(<span class="hljs-string">"ws"</span>);
<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> WebSocket.Server({ <span class="hljs-attr">port</span>: <span class="hljs-number">8080</span> });

server.on(<span class="hljs-string">"connection"</span>, <span class="hljs-function">(<span class="hljs-params">client</span>) =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Client connected to server"</span>);

 <span class="hljs-comment">//Simulate client to receive real-time updates from the server every 2 seconds</span>
 <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> message = <span class="hljs-string">`Message received at: <span class="hljs-subst">${<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toLocaleTimeString()}</span>`</span>;
  client.send(message);
 }, <span class="hljs-number">2000</span>);

 <span class="hljs-comment">// Handle client disconnection</span>
 client.on(<span class="hljs-string">"close"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">clearInterval</span>(interval);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Client disconnected"</span>);
 });
});

<span class="hljs-comment">// Client (listens for updates from server)</span>
<span class="hljs-keyword">const</span> clientSocket = <span class="hljs-keyword">new</span> WebSocket(<span class="hljs-string">"ws://localhost:8080"</span>);

clientSocket.onmessage = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Message from server: "<span class="hljs-subst">${event.data}</span>"`</span>);
};
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, we explored five key communication design patterns: Request-Response, Publish/Subscribe, Short Polling, Long Polling, and Push. </p>
<p>Each pattern has its unique strengths and limitations which makes them suitable for various use cases. </p>
<p>Depending on your application’s goal, understanding these patterns will help you design efficient backend systems.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Why You Should Use Java for Backend Development ]]>
                </title>
                <description>
                    <![CDATA[ Java is a well-established and widely-used programming language. You can use it to create desktop and mobile applications, for massive data processing, for backend development, to program embedded devices, and more. Oracle, the company that owns Java... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-for-backend-web-development/</link>
                <guid isPermaLink="false">66bae7da02a6638884966f15</guid>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ David Fagbuyiro ]]>
                </dc:creator>
                <pubDate>Thu, 09 Feb 2023 21:54:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-realtoughcandycom-11035547.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Java is a well-established and widely-used programming language. You can use it to create desktop and mobile applications, for massive data processing, for backend development, to program embedded devices, and more.</p>
<p>Oracle, the company that owns Java, claims that Java is used on 3 billion devices worldwide, making it one of the most popular programming languages.</p>
<p>In this article, we will discuss the history of Java, reasons to use Java for backend development, the top tech companies that already use Java for this purpose, and the top Java frameworks for backend development.</p>
<p>We will also explore the benefits and drawbacks of using Java for backend development.</p>
<h2 id="heading-history-of-the-java-programming-language">History of the Java Programming Language</h2>
<p>Java was launched in 1991 when James Gosling and his team at Sun Microsystems began development on the language.</p>
<p>Soon after, the team shifted its focus to developing the language for the newest specialized market, the World Wide Web.</p>
<p>Java was offered to the public in 1995 for usage in various applications ranging from the internet to computer programming. According to <a target="_blank" href="https://learntocodewith.me/">learncodewith.me</a>, Java is one of the top three programming languages in the world for backend development. It's also ranked first among the top ten programming languages for 2022.</p>
<h2 id="heading-why-you-should-use-java-for-backend-infrastructure">Why You Should Use Java for Backend Infrastructure</h2>
<p>The following are some benefits of using the Java programming language for backend development.</p>
<h3 id="heading-scalability-and-robustness">Scalability and Robustness</h3>
<p>Java has a robust type-checking mechanism that makes it durable. The Java virtual machine (JVM) enables dynamic linking and a secure environment, allowing Java to run anywhere.</p>
<p>Java's automatic memory management and disposal collection make it highly scalable and these features help speed up web application development.</p>
<h3 id="heading-open-source-library">Open Source Library</h3>
<p>The vast majority of Java libraries are free and open-source, with expert support. The use of such libraries speeds up the back-end programming of web projects dramatically.</p>
<p>There are many Java libraries for various uses, including logging, JSON parsing, unit testing, XML and HTML parsing, messaging, PDF and Excel reading, cryptography, and many others.</p>
<h3 id="heading-diversity">Diversity</h3>
<p>Java has long been the dominant programming language for developing Web applications, Android applications, and software tools such as Eclipse, IntelliJ IDEA, NetBeans IDE, and others.</p>
<p>Java's use cases have now grown to include data science applications, machine learning applications, and even IoT applications.</p>
<h3 id="heading-simplicity">Simplicity</h3>
<p>Java syntax is relatively simple, easy to develop, learn, maintain, and understand, and the code is easily debuggable.</p>
<p>Java is also less complex than languages such as C and C++ because many of these languages' sophisticated features, such as explicit pointers, storage classes, operator overloading, and many others, have been eliminated from Java.</p>
<h3 id="heading-security">Security</h3>
<p>Java reduces security concerns and dangers by reducing the use of explicit pointers. A pointer is a value that keeps the memory address of another value and can be exploited to gain unwanted memory access. This issue is solved by removing the concept of pointers.</p>
<h3 id="heading-platform-independency">Platform Independency</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-51.png" alt="image chart from techavidan" width="600" height="400" loading="lazy"></p>
<p><em>image from techavidan</em></p>
<p>Java is platform-independent, which means it's a "Write Once, Run Anywhere" (WORA) language.</p>
<p>The compiled code (the byte code of Java) is platform-independent and can run on any machine, irrespective of the operating system. We can run this code on any machine that supports the Java Virtual Machine (JVM), as shown in the figure above.</p>
<h3 id="heading-multithreading-support">Multithreading Support</h3>
<p>Java is a multithreaded language, which means that multiple threads can run at the same time.</p>
<p>A thread is a process's smallest unit. Multithreading allows us to maximize CPU use. Multiple threads share the same memory space, increasing the application's efficiency and performance.</p>
<h2 id="heading-drawbacks-of-the-java-programming-language">Drawbacks of the Java Programming Language</h2>
<h3 id="heading-lack-of-backup-facility">Lack of Backup Facility</h3>
<p>Java is primarily concerned with storage and does not prioritize data backup. This is a huge drawback, and it is losing user interest and ratings as a result.</p>
<h3 id="heading-code-complexity">Code Complexity</h3>
<p>Java code is extensive, which means it contains many words and long, complex sentences that are hard to read and comprehend. This reduces the code's readability.</p>
<p>Java strives to be more manageable, but it must settle for unnecessarily complex programs and detailed explanations for each thing.</p>
<h3 id="heading-speed-and-performance-level">Speed and Performance Level</h3>
<p>Java consumes a large amount of memory and is substantially slower than native languages such as C or C++. This is partly because each bit of code must be interpreted into machine-level code. This slow performance is caused by the JVM's additional level of compilation and abstraction.</p>
<h3 id="heading-memory-capacity">Memory Capacity</h3>
<p>When compared to other languages such as C and C++, Java uses a significant amount of memory. Memory efficiency and system performance may suffer during cleanup execution.</p>
<h2 id="heading-top-companies-that-use-java">Top Companies That Use Java</h2>
<p>To begin with the list, according to statistics based on <a target="_blank" href="https://codegym.cc/groups/posts/771-is-java-still-relevant-what-big-companies-use-it">Codegym</a>, 10,130 companies are said to employ Java in their IT stacks. Not unexpectedly, the United States leads among enterprises that use Java, accounting for more than 60% of Java clients (about 64,000 businesses).</p>
<p><strong>Linkedin:</strong> This application is primarily written in Java, with some C++ parts thrown in for good measure. Java is excellent for LinkedIn's search and analytics. More specifically, it addresses scale concerns, allowing the server to function faster while using fewer resources.</p>
<p><strong>Uber:</strong> Uber is the next big Java-based firm. The organization works with a large amount of real-time data, tracking drivers and incoming ride requests. As a result, Uber should be able to sift the data and match users swiftly. That's where Java comes in, handling requests and transmitting data as quickly as possible.</p>
<p><strong>Microsoft:</strong> Even though Java does not control Windows or anything similar, Microsoft uses it for various purposes. For example, it requires Java to construct its proprietary Edge web browser.</p>
<p><strong>NASA World Wind:</strong> NASA built the Word Wind app, which features a realistic 3D virtual globe and can display precise geographical data, largely thanks to Java (the program uses actual images from satellites to develop 3D representations of the planets). It's an open-source program that runs on practically any operating system because it's developed in Java.</p>
<p><strong>Netflix:</strong> Netflix, the same as PayPal, primarily uses Java for practically everything. And because Netflix is one of the best-known entertainment platforms in the world, there is a significant demand for Java expertise in this organization.</p>
<p>In addition to the tech titans mentioned earlier, Java is used by Airbnb, Google, eBay, Spotify, TripAdvisor, Intel, Pinterest, Groupon, Slack, Flipkart, and many more. Without a doubt, you can find Java practically anywhere.</p>
<h2 id="heading-differences-between-a-java-backend-and-a-nodejs-backend">Differences Between a Java Backend and a Node.js Backend</h2>
<p>Java and Node.js are both popular choices for building server-side applications. But they have some key differences that make each one better suited for different use cases.</p>
<p>In terms of strengths, Java has the advantage of being a statically-typed language, which provides better performance and stability. Java also provides better security features, such as the Java Virtual Machine (JVM), which has memory protection and isolation. Java also has a large number of libraries and tools available, which makes it easier to develop and maintain large-scale applications.</p>
<p>Node.js, on the other hand, has the advantage of being a dynamically-typed language, which makes it easier to learn and more flexible. Node.js is also well-suited for real-time applications, such as chat applications, thanks to its event-driven architecture. Node.js also has a large and active community, which provides a wealth of libraries and tools for various tasks.</p>
<p>In terms of weaknesses, Java can be slower to develop and more complex compared to Node.js, due to its strong typing and verbose syntax. Java also requires more memory compared to Node.js, which can make it less suitable for low-memory devices.</p>
<p>Node.js, on the other hand, has weaker type checking compared to Java, which can lead to unexpected errors. Node.js also has a single-threaded architecture, which means that it is not as well-suited for multi-threaded applications compared to Java.</p>
<p>In conclusion, both Java and Node.js have their own strengths and weaknesses for backend development. Java is well-suited for large-scale and complex applications, while Node.js is well-suited for real-time and scalable applications. The choice between the two ultimately depends on the specific requirements of the project.</p>
<h2 id="heading-top-java-frameworks-for-backend-development">Top Java Frameworks for Backend Development</h2>
<p>There are various Java backend frameworks, each with its own capabilities and features. Below are a few popular examples:</p>
<h3 id="heading-spring">Spring</h3>
<p>The Spring framework is a lightweight Java application framework and an inversion of a control container.</p>
<p>The framework's core functionality can be used by any Java application, although there are enhancements for constructing web applications on top of the Java EE framework.</p>
<h3 id="heading-hibernate">Hibernate</h3>
<p>Hibernate ORM is an object-relational mapping tool written in Java that provides a framework for translating a relational database into an object-oriented domain model.</p>
<h3 id="heading-play">Play</h3>
<p>The Play Framework combines productivity and performance, making it simple to create scalable Java and Scala online applications. Play is developer-friendly, with a "simply hit refresh" workflow and testing support built in.</p>
<p>Because of Play's stateless and non-blocking architecture, applications scale reliably. Play is ideal for current online and mobile apps because it is RESTful by default and includes asset compilers, JSON, and WebSocket support.</p>
<h3 id="heading-struts">Struts</h3>
<p>Apache Struts is a free and open-source web application framework used to create Java EE web applications. It uses and improves the Java Servlet API to encourage developers to use a model-view-controller paradigm. Craig McClanahan designed it and presented it to the Apache Nation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about the Java programming language's history. You have also learned the key distinctions between Java and Node.js, clearing up any uncertainty.</p>
<p>Finally, you understand what Java is used for, the industries in which it can be found, and some of its distinguishing traits. You can now use it in your own web apps for seamless backend development.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Front End Developer vs Back End Developer – Definition and Meaning In Practice ]]>
                </title>
                <description>
                    <![CDATA[ Websites and applications are complex! Buttons and images are just the tip of the iceberg. With this kind of complexity, you need people to manage it, but which parts are the front end developers and back end developers responsible for? [The many la... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/front-end-developer-vs-back-end-developer-definition-and-meaning-in-practice/</link>
                <guid isPermaLink="false">66b8e3260cedc1f2a4f70691</guid>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Cloud Computing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Thu, 18 Jun 2020 14:45:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/front-end-back-end.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Websites and applications are complex! Buttons and images are just the tip of the iceberg. With this kind of complexity, you need people to manage it, but which parts are the front end developers and back end developers responsible for?</p>
<ul>
<li>[The many layers of development](#The many layers of development)</li>
<li><a class="post-section-overview" href="#heading-but-were-not-all-full-stack">But we’re not all full stack</a></li>
<li><a class="post-section-overview" href="#heading-so-what-is-the-difference-between-front-end-development-and-back-end-development">So what is the difference between Front End Development and Back End Development?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-front-end-development">What is Front End Development?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-back-end-development">What is Back End Development?</a></li>
<li><a class="post-section-overview" href="#heading-where-things-get-fuzzy">Where things get fuzzy</a></li>
<li><a class="post-section-overview" href="#heading-resources-to-learn">Resources to learn</a></li>
</ul>
<h2 id="heading-the-many-layers-of-development">The many layers of development</h2>
<p>Whether you’re working on a website or a native iOS app, all development environments share a common theme — there’s a front end to an application and a back end.</p>
<p>This line can get blurry, especially given the rise of javascript and the <a target="_blank" href="https://en.wikipedia.org/wiki/Serverless_computing">serverless</a> world. With the tooling somewhat merging together, we might sometimes wonder if we’re a <a target="_blank" href="https://www.colbyfayock.com/2020/02/how-to-become-a-full-stack-web-developer-in-2020/">full stack developer</a>.</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/holtbt/status/977419276251430912"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<h2 id="heading-but-were-not-all-full-stack">But we’re not all full stack</h2>
<p>As much as we might all <a target="_blank" href="https://full-stack.netlify.app/">want to be</a>, we’re not all full stack developers. Personally, I find myself able to be productive in the back end of an application, but it’s not my strength and I much prefer to be heads down building UIs.</p>
<p>And some people are the opposite, where they are strongest dealing with building APIs in the back end of an application and while they can build out a UI, it might be more of a prototype-like experience than a fleshed out application.</p>
<h2 id="heading-so-what-is-the-difference-between-front-end-development-and-back-end-development">So what is the difference between Front End Development and Back End Development?</h2>
<p>Even if you are a full stack developer, that doesn’t mean there’s not a division of responsibilities.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/front-end-vs-back-end-engineer-2.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Front End Engineer vs Back End Engineer</em></p>
<p>So what do those look like?</p>
<h2 id="heading-what-is-front-end-development">What is Front End Development?</h2>
<p>The front end of an application typically refers to the layer that represents the UI (user interface). This can include anything from a static site with HTML and CSS to a full <a target="_blank" href="https://reactjs.org/">React</a> app that powers the UI.</p>
<h3 id="heading-what-did-front-end-development-traditionally-look-like">What did Front End Development traditionally look like?</h3>
<p>Javascript currently rules the front end web, but that wasn’t always the case. While it could have been used to add little bits of interaction to a site, typically front ends were rendered using server-side templating languages like framework-driven <a target="_blank" href="https://www.php.net/">PHP</a> and <a target="_blank" href="http://www.template-toolkit.org/">Template Toolkit</a> (<a target="_blank" href="https://www.perl.org/">Perl</a>).</p>
<p>This grew to be super popular in practice with home grown frameworks or tools like <a target="_blank" href="https://wordpress.org/">Wordpress</a> that used PHP to drive a massive community of developers who built their websites with those tools.</p>
<p>The way it worked was the templating language was able to get its data straight from the server as it was rendered. When a browser requested the page directly from the origin (the server itself), whatever data the template would need, the application logic would provide at that time.</p>
<p>Some of the more traditional front end tools include:</p>
<ul>
<li>Libraries like <a target="_blank" href="https://jquery.com/">jQuery</a> or <a target="_blank" href="https://mootools.net/">MooTools</a></li>
<li>Website frameworks like <a target="_blank" href="https://wordpress.com/">Wordpress</a></li>
<li>Plain <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS">CSS</a></li>
<li>Abundant use of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table">Table</a> elements</li>
</ul>
<p>But as time went on, javascript kept getting more mature as a language and browsers kept getting more powerful, which led to the idea that we could move more of that work to the browser to build faster and more interactive experiences.</p>
<h3 id="heading-what-does-front-end-development-look-like-now">What does Front End Development look like now?</h3>
<p>Now it’s common to see javascript-heavy websites and apps built using UI frameworks like <a target="_blank" href="https://reactjs.org/">React</a>, <a target="_blank" href="https://vuejs.org/">Vue</a>, and <a target="_blank" href="https://angular.io/">Angular</a>. These tools provide abstractions that allow developers to build complex UIs with reusable patterns like components.</p>
<p>When the browser loads the page, the page receives an initial HTML document that also includes the script tag to the javascript (same as always). But once that javascript loads, it reaches out to APIs using browser requests that when completed, update the page to fill in any kind of dynamic data that you’d typically get along with that first HTML document.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/building-website-with-more-steps.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>It's like building a website... with more steps</em></p>
<p>While it sounds like more steps, it commonly provides a faster initial page load and render, not to mention it has a great developer experience. By delivering less on that first request and prioritizing what loads after that, it usually ends up as a better user experience.</p>
<p>Some of the front end tools that are more common and growing in popularity  include:</p>
<ul>
<li>UI frameworks like <a target="_blank" href="https://reactjs.org/">React</a> or <a target="_blank" href="https://vuejs.org/">Vue</a></li>
<li>Web frameworks like <a target="_blank" href="https://www.gatsbyjs.org/">Gatsby</a></li>
<li>Compilers like <a target="_blank" href="https://babeljs.io/">Babel</a></li>
<li>Bundlers like <a target="_blank" href="https://webpack.js.org/">Webpack</a></li>
<li>CSS tools like <a target="_blank" href="https://sass-lang.com/">Sass</a></li>
</ul>
<p>But those APIs, whether ones we pay for or create ourselves, need to be built <em>somewhere</em>. That’s where the back end comes in.</p>
<h2 id="heading-what-is-back-end-development">What is Back End Development?</h2>
<p>The back end layer is usually where the business logic occurs. This can be super complex like the rules that determine revenue for an e-commerce company or something more common like a user profile.</p>
<h3 id="heading-what-did-back-end-development-traditionally-look-like">What did Back End Development traditionally look like?</h3>
<p>The back ends of applications were historically built using server-side languages like <a target="_blank" href="https://www.php.net/">PHP</a> or <a target="_blank" href="https://www.ruby-lang.org/en/">Ruby</a>. The idea is that you have a server that you need to perform complex operations on, so the way to do that is with a language that server would understand.</p>
<p>On each request to the server, the backend would perform the full stack of the operations, including rendering out the front end. By using frameworks or DIY architectures, the back end would accept the request, figure out what it should do with that request, run any business logic needed with the request, and provide the front end any data that it would need to display a response to that request.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/front-end-back-end-500-error.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Back end giving the front end a 500 Internal Server Error</em></p>
<p>Some of the more traditional back end tools include:</p>
<ul>
<li>On-premise or remotely managed servers like <a target="_blank" href="https://www.rackspace.com/">Rackspace</a></li>
<li>HTTP servers using <a target="_blank" href="https://httpd.apache.org/">Apache</a></li>
<li>Databases like <a target="_blank" href="https://www.mysql.com/">MySQL</a></li>
<li>Server side languages like <a target="_blank" href="https://www.php.net/">PHP</a> or <a target="_blank" href="https://www.perl.org/">Perl</a></li>
<li>Application frameworks like <a target="_blank" href="https://rubyonrails.org/">Ruby on Rails</a></li>
</ul>
<h3 id="heading-what-does-back-end-development-look-like-now">What does Back End Development look like now?</h3>
<p>Back end stacks look somewhat similar to the way they did before, aside from newer code patterns, except more often you’ll see the back ends provide data through APIs via HTTP requests instead of directly to the templates the front end team are working on.</p>
<p>While the foundation isn’t super different, it actually be comes increasingly complex as you have to deal with different security implications that could compromise your system if not properly configured such as leaving an API open to the public that returns sensitive user data.</p>
<p>But also how the server operates can be completely different. While previously, we might run our python on our own managed server (we still can), we can now make use of serverless functions with tools like <a target="_blank" href="https://aws.amazon.com/lambda/">AWS Lambda</a> that simplify how we manage code.</p>
<p>While “<a target="_blank" href="https://en.wikipedia.org/wiki/Serverless_computing">serverless</a>” doesn’t necessarily mean there are literally no servers, it means that as a service, the developer doesn’t have to worry about maintaining that server and can instead just focus on the code they need to run.</p>
<p>Some of the back end tools that are more common and growing in popularity include:</p>
<ul>
<li>Cloud servers like <a target="_blank" href="https://aws.amazon.com/ec2/">AWS EC2</a></li>
<li>Serverless services like <a target="_blank" href="https://aws.amazon.com/lambda/">AWS Lambda</a></li>
<li>NoSQL databases like <a target="_blank" href="https://www.mongodb.com/">MongoDB</a></li>
<li>Languages like <a target="_blank" href="https://www.python.org/">Python</a> or javascript via <a target="_blank" href="https://nodejs.org/">NodeJS</a></li>
<li>Web application frameworks like <a target="_blank" href="https://www.serverless.com/">Serverless Framework</a></li>
</ul>
<h2 id="heading-where-things-get-fuzzy">Where things get fuzzy</h2>
<p>Part of the twist with back ends is now you can write your back end with javascript. With the inception of <a target="_blank" href="https://nodejs.org/en/">Node.js</a>, developers were given the ability to use their favorite browser language to do most of the same things they were used to and familiar with but now on a server.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/nodejs-never-stopped-to-think-if-should.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Never stopped to think if we should write JS on a server</em></p>
<p>While not everyone is fond of running javascript as a server side language, it became a little easier to use the same language to write the full stack of an application. This changed the game a bit as far as front ends and back ends were concerned.</p>
<p>But it’s also started to come full circle where you now see systems that build APIs right <a target="_blank" href="https://redwoodjs.com/tutorial/redwood-file-structure">next to the front end</a> similar to what you might see in a traditional stack.</p>
<h2 id="heading-front-end-vs-back-end">Front End vs Back End</h2>
<p>Regardless of the stack, there will always be the separation of concerns. The UI and all of the interaction, whether rendered on the server or in the browser, is what makes the front end the front end and the data and business logic, whether coming from the server in your company’s closet or a managed function, is what makes the back end the back end.</p>
<p>Whether you prefer to work on the user facing features or build the logic that lets them do things, there are plenty of resources to get started.</p>
<h2 id="heading-resources-to-learn">Resources to learn</h2>
<h3 id="heading-front-end">Front End</h3>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/learn/">freecodecamp.org Responsive Web Design Certification</a> (freecodecamp.org)</li>
<li><a target="_blank" href="https://beginnerjavascript.com/">Beginner Javascript</a> (beginnerjavascript.com - Wes Bos)</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=Ke90Tje7VS0">React Tutorial for Beginners</a> (youtube.com - Programming with Mosh)</li>
<li><a target="_blank" href="https://frontendmasters.com/">Front End Masters</a> (frontendmasters.com)</li>
</ul>
<h3 id="heading-back-end">Back End</h3>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/learn">freecodecamp.org APIs and Microservices Certification</a> (freecodecamp.org)</li>
<li><a target="_blank" href="https://kentcdodds.com/blog/super-simple-start-to-serverless/">Super simple start to serverless</a> (kentcdodds.com)</li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/aws-certified-cloud-practitioner-training-2019-free-video-course/">AWS Certified Cloud Practitioner Training 2019 - A Free 4-hour Video Course</a> (freecodecamp.org)</li>
<li><a target="_blank" href="https://www.edx.org/course/cs50s-introduction-to-computer-science">CS50's Introduction to Computer Science</a> (edx.org)</li>
</ul>
<h3 id="heading-all-the-above">All the above</h3>
<ul>
<li><a target="_blank" href="https://www.colbyfayock.com/2020/02/how-to-become-a-full-stack-web-developer-in-2020/">How to Become a Full Stack Web Developer in 2020</a> (colbyfayock.com)</li>
<li><a target="_blank" href="https://egghead.io/?af=atzgap">Egghead.io</a> (egghead.io)</li>
<li><a target="_blank" href="https://www.100daysofcode.com/">100 Days of Code</a> (100daysofcode.com)</li>
<li><a target="_blank" href="https://www.udemy.com/course/the-web-developer-bootcamp/">The Web Developer Bootcamp</a> (udemy.com - Colt Steele)</li>
</ul>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">?️ Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
  </ul>
</div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Best Way to Learn Backend Web Development ]]>
                </title>
                <description>
                    <![CDATA[ By Mehul Mohan My previous article described how you can get into frontend development. It also discussed how the front end can be a place filled with landmines – step in the wrong place and you'll be overwhelmed by the many frameworks of the JavaScr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-backend-development/</link>
                <guid isPermaLink="false">66d46062733861e3a22a733b</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 12 Apr 2020 14:38:22 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9bab740569d1a4ca2d39.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mehul Mohan</p>
<p>My previous article described <a target="_blank" href="https://www.freecodecamp.org/news/learn-frontend-web-development/">how you can get into frontend development</a>. It also discussed how the front end can be a place filled with landmines – step in the wrong place and you'll be overwhelmed by the many frameworks of the JavaScript ecosystem. </p>
<p>In this blog article, let's see how you can get into back end development. Along the way, I'll answer some of the most common questions people ask me about it.</p>
<h2 id="heading-what-is-backend-development">What is Backend Development?</h2>
<p>Front end development involves what a user sees on the screen when they open a specific URL owned by you. Even in a completely static environment (with only HTML/CSS), when someone opens a website, some server on the planet needs to respond to you with those HTML and CSS files. </p>
<p>That server is just a computer, just like the one you use yourself to browse the internet. But it has been tuned for performance, and doesn't have unnecessary components like a mouse or keyboard attached. And it sits with tons of other computers probably in a data warehouse. </p>
<p>Programming those computers in some special way is called <strong>back end development</strong>.</p>
<p>You may think that backend development is called what it is because it runs behind the user's back. A visitor to your website never really "accesses" the back end completely. They just communicate with your server, either directly through ports for very limited access (like transferring HTML/CSS files) or not even that – buried deep under CDNs or firewalls (like Cloudflare).</p>
<p>Now that we have a raw understanding of what back end development means, let's get into some <strong>real</strong> questions.</p>
<h2 id="heading-is-front-end-programming-knowledge-required-for-the-back-end">Is front end programming knowledge required for the back end?</h2>
<p><strong>TLDR;</strong> No.</p>
<p>Back end development, as mentioned above, involves the programming of a computer sitting probably on the other side of the planet responsible for responding to what your users say from their own computers. </p>
<p>If you're a full-time backend developer, you do not really need to care about what goes on inside those HTML, CSS and JavaScript files you send to the user's browser. Instead, you've to focus more on the performance of the server, the server code, and throughput.</p>
<h2 id="heading-what-goes-into-back-end-development">What goes into back end development?</h2>
<p>Well, going by the books, you may say that a person who codes an application that can respond to HTTP requests is a back end developer. </p>
<p>But in reality, sometimes back end developers are able to do much more than just writing server scripts. They have the knowledge to set up reverse proxy servers (NGiNX/HAProxy), enable compression and other ways to speed up the site, and set up a production docker environment.</p>
<p>To qualify as a back end developer, I'd say the bare minimum skills you need are:</p>
<ol>
<li>Good knowledge about a programming language in which you can write HTTP servers. Examples: C#, Java, Node, PHP, Python, etc. (there are many!)</li>
<li>Manage to host using cPanel (traditional) or using bash terminal (cloud hosting/traditional)</li>
<li>Working with Version Control Systems (VCS) like git for managing and deploying builds</li>
</ol>
<p>Just like every game comes with minimum and recommended specifications, for back end developers, my recommend specifications would be (inclusive of the minimum skills):</p>
<ol>
<li>NGiNX for static file assets and server management</li>
<li>Database Management skills (SQL/NoSQL)</li>
<li>Security of backend (Writing safe and robust code, running applications in docker containers with limited privileges, protection against DoS attacks)</li>
<li>Autoscaling/Load balancing</li>
</ol>
<p>Alright, too much talking about what goes into back end development. But how do you become one?</p>
<h2 id="heading-start-with-minimum-requirements">Start with minimum requirements</h2>
<p>Like I said, for the back end, just like games, we have a set of minimum requirements and recommended requirements. The minimum requirements consists of 3 things:</p>
<h3 id="heading-learn-a-backend-programming-language">Learn a backend programming language</h3>
<p>When people learn by themselves, they usually do not have a team or anyone who can do front end development. They're all on their own. So you'll often have to create webpages and servers all by yourself, at least in the beginning. </p>
<p>Although there are a lot of choices for back end programming languages, and I cannot think of any popular system language which doesn't support HTTP servers out of the box. The advantage of choosing Node is that your front end JavaScript skills are transferrable to the back end.</p>
<p>Nonetheless, you can choose from a variety of languages like Java, C++, C#, Python, PHP, etc.</p>
<p>How do you pick one, you might ask. The answer is the same as it was in the front end development article: you have gotta try everything initially and see which one clicks the best with you. </p>
<p>Node is easy as you might have already done JS programming for the front end. But if you're a Python or Java developer, you might find those easy to pick up. It depends on your profession and taste completely.</p>
<h3 id="heading-learn-about-managing-hosting">Learn about managing hosting</h3>
<p>Gone are the days when you'll have to manually purchase servers and set them up in your home, connect to your ISP, do all that stuff yourself. This is the era of cloud computing. Now, when hosting your website, you have mainly 2 options:</p>
<ol>
<li>Going for managed hosting servers like HostGator or GoDaddy.</li>
<li>Going for cloud hosting providers like GCP, AWS, or DigitalOcean.</li>
</ol>
<p>What is the difference between the two? In both cases, the servers are owned and operated by the respective companies. But the major difference is that managed hosting is more GUI friendly, has a rich set of tools for seeing the filesystem, monitoring usage, managing your official domain emails, uploading/downloading files from your server, and so on. It's basically a setup for people with less technical skills. </p>
<p>For that reason, I do not recommend managed sites like HostGator or GoDaddy for seasoned developers. Still, it might be a good platform to make mistakes and learn on, primarily because you usually have prepaid plans for them. You'll also have a nice UI for managing things, which doesn't allow you to accidentally shoot up your bills.</p>
<p>But when you start picking up speed, I recommend that you switch to a cloud provider. This takes away all the nice tools from cPanel that you used to manage files and folders on servers. But at the same time, it will challenge you to level up your skills a lot. </p>
<p>Today, a lot of cloud providers offer a decent free trial, too, so that you can actually try out their platform before going full in. I host my website for developers - codedamn - on DigitalOcean and find it to be at a sweet balance of site complexity and features. </p>
<p>You can use <a target="_blank" href="https://m.do.co/c/2c4c3ec5405a">this link to signup</a> on DigitalOcean and get <strong>free $100 credits</strong>. DigitalOcean instances are as cheap as $5 a month, so you have a runway of about 20 months on that instance, great deal, huh?</p>
<p>Anyway, you can choose any cloud provider. Then it's important to learn to manage the server using just the command line by ssh'ing into it.</p>
<h3 id="heading-learn-about-version-control-systems">Learn about Version Control Systems</h3>
<p>There are other solutions apart from Git for VCS. But Git is the most used and simplest to understand. </p>
<p>As an individual, you might not appreciate it right away. But you'll understand why it is so important the moment you start working either in a team on multiple features simultaneously in your project. </p>
<p>Git allows you to manage your workflow using commits and branches. Commits are like <strong>checkpoints</strong> in your codebase - the ones you can always revert to if you screw up. </p>
<p>Branches are like <strong>alternate realities</strong> of your project, where something completely different could happen. These alternate realities can be created from any point in time and can be merged back again at any time. </p>
<p>If those realities can be merged together with compatibility, then it's fine. But if there's a conflict (like if you're alive in one reality and dead in other), then you have to manually make a choice. Other changes can be merged automatically.</p>
<p>Git is super interesting, and once you get hang of it, you'll want to use it in every project. You get to keep a history of your work in an efficient manner (it compresses and stores only the difference between commits). </p>
<p>It also allows you to create online git repositories on sites like GitHub, which acts as a central source of truth for your website. Sites like GitHub can be configured with special webhooks that can actually update your website whenever you add a new checkpoint (a new commit) without you ever needing to manually go to the server and update it yourself.</p>
<h2 id="heading-go-for-recommended-skills">Go for recommended skills</h2>
<p>I'm a big believer in learning by doing. And the best way to do something comes out of necessity or interest. Once you consider yourself good enough with the minimum requirements, it's time to acquire the recommended skills. This includes all the tools like Docker and NGiNX mentioned above. </p>
<p><strong>DevOps</strong> is also something which fits in super nicely with back end developers. You could try and explore <strong>TravisCI</strong> or <strong>CircleCI</strong> for automated build deployments. Continuous Integration and Deployment (CI/CD) is a topic that could take another whole blog post, so I'll not get into that. In fact, once it is set up correctly, it'll save you a ridiculous amount of developer time!</p>
<p>Then comes databases, which I placed in recommended skills. But you're gonna need databases for pretty much any application which involves some sort of data persistence generated by the user. </p>
<p>Databases are usually easy to begin working with, but harder to maintain and tweak properly. The best way to start working on a back end tech stack is to have everything together on a single server - the code of your application, the reverse proxy servers, the database, etc. Then as you become more proficient in each thing, you can decouple it from the existing business logic. </p>
<p>By doing this, you're enabling an architecture that can be highly scaled. A database-operation intensive application could have an optimized solution for databases. And a heavy traffic bound site should have a good CDN mechanism to offload static assets, and so on.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>There's so much to learn, but it's all achievable if you don't give up. Let me know what you think about this post through my <a target="_blank" href="https://twitter.com/mehulmpt"><strong>twitter</strong></a> and <a target="_blank" href="https://instagram.com/mehulmpt"><strong>Instagram</strong></a> handles. It'll mean a lot to me if we connect over there! </p>
<p>Also, if you're interested, checkout <a target="_blank" href="https://codedamn.com"><strong>codedamn</strong></a> - a developer-focused platform for learning technologies like backend development! I even posted a <a target="_blank" href="https://www.youtube.com/watch?v=IOTL7RqUZEU">YT video on spinning up your own simple website server in 2 minutes</a>! Check that out and let me know what you think!</p>
<p>Peace!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ I rebuilt the same web API using Express, Flask, and ASP.NET. Here's what I found. ]]>
                </title>
                <description>
                    <![CDATA[ By M. S. Farzan I've been shopping around for a back end framework to support a tabletop game app, and decided to do some research to determine the best fit for my needs.  The objective was straightforward: to build a simple RESTful API that would al... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/i-built-a-web-api-with-express-flask-aspnet/</link>
                <guid isPermaLink="false">66d851f5248f4119381de123</guid>
                
                    <category>
                        <![CDATA[ Aspnetcore ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Back end development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Flask Framework ]]>
                    </category>
                
                    <category>
                        <![CDATA[ full stack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 29 Feb 2020 19:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9c5c740569d1a4ca31ac.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By M. S. Farzan</p>
<p>I've been shopping around for a back end framework to support a <a target="_blank" href="https://www.nightpathpub.com/entromancy">tabletop game app</a>, and decided to do some research to determine the best fit for my needs. </p>
<p>The objective was straightforward: to build a simple <a target="_blank" href="https://restfulapi.net/">RESTful API</a> that would allow a front end app to perform basic <a target="_blank" href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> operations, providing me with an introduction to what the development process would look like.</p>
<p>There are a lot of back end framework options out there, and I'm most familiar with JavaScript, C#, and Python (in that order), which limited my options somewhat.  The natural starting point was to build a simple front end that would send requests to an API, which would in turn read from and write to a local database.</p>
<p>I began my development process with Express, which, for reasons I'll soon explain, led me to also check out Flask and ASP.NET. I thought my findings might prove useful to others out there who are researching back end frameworks for small projects. In this article, I'll also provide code examples and the resources that I used to build everything.</p>
<p>You can access the full code on <a target="_blank" href="https://github.com/sominator/web-api-project">GitHub</a>, as well.</p>
<p>I should caveat that I won't be promoting one framework over another, and haven't yet compared things like deployment, authentication, or scalability.  Your mileage may vary if those particulars are important to you!</p>
<p>I will, however, provide a <strong>TL;DR</strong> at the bottom if you just want to get the summary and key learnings.</p>
<p>Here we go!</p>
<h2 id="heading-defining-the-api">Defining the API</h2>
<p>If you're new to web development, you might be asking, "what's an API?"</p>
<p>I've had to ask the question a hundred times to find an answer that made sense. And it really wasn't until I built my own that I could say I understood what an API <em>does</em>.</p>
<p>Put simply, an API, or "application programming interface", allows two different computing systems to talk to one another. In this article, I'll show a simple front end app that displays a "quest" tracker that players can view for their tabletop roleplaying game. Each quest has a "name" and a "description," both of which are displayed in the web browser.</p>
<p>If I already had all of the quests listed on the website and just wanted players to view them, I would have no need for an API or back end. For this project, however, I want the ability to allow users to add quests, search for them, delete them, and so on. For those operations, I need to store the quests somewhere, but my front end app isn't able to transfer information directly to a database.</p>
<p>For that, I need an API that can receive HTTP requests from the website, figure out what to do with those requests, interact with my database, and send more information back up the chain so that the user can see what happened.</p>
<p>The whole thing - the front end "client", the back end "API" or server, and the database - is called a "stack," or more precisely, the "full stack." For this project, I built a simple front end website as the top of the stack, and switched out everything beneath it as I tried out different frameworks and databases.</p>
<h2 id="heading-project-structure">Project Structure</h2>
<p>The structure for this project was fairly simple, with the front end client separated from three different servers that I would spin up as necessary to serve the API.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/Project-Structure.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I used <a target="_blank" href="https://visualstudio.microsoft.com/vs/community/">Visual Studio Community</a> as my code editor and IDE, with the requisite language packages installed for JavaScript, Python, and C#.</p>
<p>I'll provide an overview of my experience with each framework in turn, with links to the tutorials and packages that I used to get them to work with the client. But first, let's take a look at the front end!</p>
<h2 id="heading-the-client-vuejs">The Client: Vue.js</h2>
<p>The goal for the client was to have a simple website that would receive information from the database through the API and display it to the user. To streamline the process, my requirements were that the client would only need to "read" all of the items in the database, and provide the user with the ability to "create" a new quest.  </p>
<p>These "read" and "create" operations - the "R" and "C" in "CRUD" - are analogous to the HTTP methods of "GET" and "POST," which we'll see in the code below.</p>
<p>In front end development, I'm most comfortable using <a target="_blank" href="https://vuejs.org/">Vue</a>, and used the <a target="_blank" href="https://cli.vuejs.org/">Vue CLI</a> to scaffold a basic client, with the following file structure:   </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/Client-Structure.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I replaced the boilerplate markup provided by the Vue CLI with the following:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>RPG Quests<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"(quest, index) in quests"</span> <span class="hljs-attr">v-bind:key</span>=<span class="hljs-string">"index"</span>&gt;</span>{{quest.name}}: {{quest.description}}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"newQuestName"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Quest Name"</span> /&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"newQuestDescription"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Quest Description"</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">v-on:click</span>=<span class="hljs-string">"postQuest"</span>&gt;</span>Add Quest<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>
</code></pre>
<p>And the corresponding Vue code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>;

    <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
        <span class="hljs-attr">name</span>: <span class="hljs-string">'App'</span>,
        <span class="hljs-attr">data</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            <span class="hljs-keyword">return</span> {
                <span class="hljs-attr">quests</span>: <span class="hljs-literal">null</span>,
                <span class="hljs-attr">newQuestName</span>: <span class="hljs-literal">null</span>,
                <span class="hljs-attr">newQuestDescription</span>: <span class="hljs-literal">null</span>
            }
        },
        <span class="hljs-attr">methods</span>: {
            <span class="hljs-attr">getQuests</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
                axios
                    .get(<span class="hljs-string">'http://localhost:3000/quests'</span>)
                    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> (<span class="hljs-built_in">this</span>.quests = response.data));
            },
            <span class="hljs-attr">addQuest</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
                axios
                    .post(<span class="hljs-string">'http://localhost:3000/quests'</span>, {
                        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.newQuestName,
                        <span class="hljs-attr">description</span>: <span class="hljs-built_in">this</span>.newQuestDescription
                    });
            },
            <span class="hljs-attr">postQuest</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
                axios.all([<span class="hljs-built_in">this</span>.addQuest(), <span class="hljs-built_in">this</span>.getQuests()]);
                <span class="hljs-built_in">this</span>.$forceUpdate();
            }
        },
        <span class="hljs-attr">mounted</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">this</span>.getQuests();
        }
    }
</code></pre>
<p>If you're not familiar with Vue, the specifics of the front end aren't that important! Of significance here is that I'm using a JavaScript package called <a target="_blank" href="https://github.com/axios/axios">Axios</a> to make my GET and POST requests to a potential server. </p>
<p>When the client loads, it'll make a GET request to the URL http://localhost:3000/quests to load all quests from the database. It also provides a couple of input fields and a button that will POST a new quest.</p>
<p>Using the Vue CLI to serve the client on http://localhost:8080, the front end of the app looks like this in action:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/Client.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once quests are added to the database, they'll start appearing in between the "RPG Quests" header and the input fields.</p>
<h3 id="heading-client-resources">Client Resources</h3>
<p>To build the client, I used:</p>
<ul>
<li><a target="_blank" href="https://nodejs.org/en/">NodeJS</a>/<a target="_blank" href="https://www.npmjs.com/">NPM</a> for package management</li>
<li><a target="_blank" href="https://cli.vuejs.org/">Vue CLI</a> for scaffolding, serving, and building projects</li>
<li><a target="_blank" href="https://github.com/axios/axios">Axios</a> for making HTTP requests to the API</li>
<li><a target="_blank" href="https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html">Vue Axios Documentation</a> for making sense of how to use Axios in concert with the API</li>
<li><a target="_blank" href="https://www.postman.com/">Postman</a> for testing API requests through the browser before implementing them in the client.</li>
</ul>
<h2 id="heading-javascript-api-express">JavaScript API: Express</h2>
<p><a target="_blank" href="https://expressjs.com/">Express</a> is a lightweight web framework for <a target="_blank" href="https://nodejs.org/en/">NodeJS</a> that allows you to write server-side applications with JavaScript.</p>
<p>It's un-opinionated, which means that you can build your applications how you like without it defining the architecture for you. You can add packages to improve functionality as you fancy, which I found to be a double-edged sword as a newbie to the framework. More on that later.</p>
<p>Being most comfortable in JavaScript, I was excited by the prospect of having the entire stack run on just one language instead of several. I had heard of the "MEVN Stack," which denotes a full stack application that is comprised of <a target="_blank" href="https://www.mongodb.com/">MongoDB</a>, Express, Vue, and NodeJS, and decided to try that out for this iteration of the project.</p>
<p>I followed a <a target="_blank" href="https://dev.to/beznet/build-a-rest-api-with-node-express-mongodb-4ho4">web API tutorial</a> to first build a template app, then used another <a target="_blank" href="https://medium.com/@anaida07/mevn-stack-application-part-1-3a27b61dcae0">MEVN tutorial</a> to fill in the details of how to get the API to communicate with the Vue client that I had built. The Express API that I created for this project follows a similar structure to the former, using MongoDB as the database:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/Express-Structure.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you're coming from a JavaScript background, Express is fairly easy to read, even if you're not familiar with some of the back end terminology. The following is a snippet from /routes/quests.js, for example, which handles the HTTP <a target="_blank" href="https://en.wikipedia.org/wiki/Web_API#Endpoints">endpoint</a> requests:</p>
<pre><code class="lang-javascript">router.get(<span class="hljs-string">'/'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> quests = <span class="hljs-keyword">await</span> Quest.find();
        res.json(quests);
    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: err.message });
    }
});

router.post(<span class="hljs-string">'/'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> quest = <span class="hljs-keyword">new</span> Quest({
        <span class="hljs-attr">name</span>: req.body.name,
        <span class="hljs-attr">description</span>: req.body.description
    });
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> newQuest = <span class="hljs-keyword">await</span> quest.save();
        res.status(<span class="hljs-number">201</span>).json(newQuest);
    } <span class="hljs-keyword">catch</span> (err) {
        res.status(<span class="hljs-number">400</span>).json({ <span class="hljs-attr">message</span>: err.message });
    }
});
</code></pre>
<p>The general theme of the code is to receive a request, attempt to contact the database to do work, and then send a response back to whoever's asking. The specifics can be quite complex, particularly if you're writing your own <a target="_blank" href="https://expressjs.com/en/guide/using-middleware.html">middleware</a> that does things in between the request and response, but the code is at least readable.</p>
<p>I found MongoDB to be painless to work with as a <a target="_blank" href="https://www.mongodb.com/nosql-explained">NoSQL</a> database.  If you're working with Express, you'll most likely use <a target="_blank" href="https://mongoosejs.com/">Mongoose</a> as an <a target="_blank" href="https://en.wikipedia.org/wiki/Object-relational_mapping#Object-oriented_databases">ODM</a> - basically like a "middle person" that translates a model of what your data looks like to the database.</p>
<p>The model in this app (called a "schema" in Mongoose terms) is really simple, located in /models/quests.js:</p>
<pre><code class="lang-language">const questSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
});
</code></pre>
<p>The above indicates that the database should store our two fields: a quest name and a quest description.  Both of these fields are strings, and required. All GET and POST requests will have to conform to this model to interact with the database.</p>
<p>After wiring all of this up and POSTing a few new quests, the front end site started populating with data:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/Vue-Front-End-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The process of setting up the Express API was not without its hair pulling, however. Being a primarily front end and 2D game developer, I've become intimately familiar with how dispersed the JavaScript ecosystem can feel. This frustration was magnified in attempting to build a back end app. There are a <em>lot</em> of packages required to get everything up and running, each of which having its own required configuration and implementation.</p>
<p>If you're looking for a framework that just does everything out of the box, Express is most certainly not the choice for you. It's lightweight, flexible, and easy to read, in a very "choose-your-own-adventure" fashion. I quite like how clean the code is and the ability to structure my projects as I see fit, but troubleshooting and error handling do leave a lot to be desired.</p>
<h3 id="heading-javascriptexpress-resources">JavaScript/Express Resources</h3>
<p>To build the JavaScript API, I used:</p>
<ul>
<li><a target="_blank" href="https://nodejs.org/en/">NodeJS</a>/<a target="_blank" href="https://www.npmjs.com/">NPM</a> for package management</li>
<li><a target="_blank" href="https://expressjs.com/">Express</a> as the main web framework</li>
<li><a target="_blank" href="https://www.npmjs.com/package/dotenv">Dotenv</a> to create environment-specific variables</li>
<li><a target="_blank" href="https://nodemon.io/">Nodemon</a> to watch files for changes and restart the server so I didn't have to</li>
<li><a target="_blank" href="https://expressjs.com/en/resources/middleware/cors.html">CORS</a> to allow for <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">cross-origin requests</a> (basically a pain if you're trying to make requests from a client to a server that are both running locally on your machine)</li>
<li><a target="_blank" href="https://www.mongodb.com/">MongoDB</a> for the <a target="_blank" href="https://www.mongodb.com/nosql-explained">NoSQL</a> database</li>
<li><a target="_blank" href="https://mongoosejs.com/">Mongoose</a> for writing models that map onto MongoDB </li>
<li><a target="_blank" href="https://dev.to/beznet/build-a-rest-api-with-node-express-mongodb-4ho4">This API tutorial</a> to provide a basic understanding of how to create an Express-MongoDB stack</li>
<li><a target="_blank" href="https://medium.com/@anaida07/mevn-stack-application-part-1-3a27b61dcae0">This MEVN tutorial</a> to fill in the gaps of running a MongoDB-Express-Vue-Node full stack</li>
</ul>
<h2 id="heading-python-api-flask">Python API: Flask</h2>
<p>In the process of building the Express API, I had a conversation with a data science friend who works in Python. This gave me the idea of trying out non-JavaScript frameworks to see if they were better suited for my app.</p>
<p>I took a cursory look at <a target="_blank" href="https://www.djangoproject.com/">Django</a>, since I'd been hearing about it as a powerhouse back end framework that provides everything out of the box. I was a little intimidated by how opinionated it seemed, and opted to try out <a target="_blank" href="https://palletsprojects.com/p/flask/">Flask</a> instead, which kind of felt like the Python equivalent of Express.</p>
<p>I followed the first few bits of the excellent <a target="_blank" href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world">Flask Mega-Tutorial</a> to get my app structure set up, using the companion <a target="_blank" href="https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask">RESTful API tutorial</a> to fill in the pieces of HTTP requests. The file structure turned out to be only a shade more complex than that of the Express API:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/Flask-Structure.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The tutorial I followed uses <a target="_blank" href="https://www.sqlite.org/index.html">SQLite</a> for its database, with <a target="_blank" href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/">Flask-SQLAlchemy</a> as an <a target="_blank" href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a>. The HTTP request code that's most analogous to the Express API is located in /app/routes.py:</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.route('/quests', methods=['GET'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_quests</span>():</span>
    questQuery = Quest.query.all()
    quests = {}
    <span class="hljs-keyword">for</span> quest <span class="hljs-keyword">in</span> questQuery:
        quests[quest.name] = quest.description
    <span class="hljs-keyword">return</span> jsonify(quests)

<span class="hljs-meta">@app.route('/quests', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">post_quest</span>():</span>
    newQuest = Quest(name=request.json[<span class="hljs-string">'name'</span>], description=request.json[<span class="hljs-string">'description'</span>])
    db.session.add(newQuest)
    db.session.commit()
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Quest Added!"</span>
</code></pre>
<p>Similarly, the database model (akin to the Mongoose "schema") is in /app/models.py:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Quest</span>(<span class="hljs-params">db.Model</span>):</span>
    name = db.Column(db.String(<span class="hljs-number">256</span>), primary_key=<span class="hljs-literal">True</span>, index=<span class="hljs-literal">True</span>, unique=<span class="hljs-literal">True</span>)
    description = db.Column(db.String(<span class="hljs-number">256</span>), index=<span class="hljs-literal">True</span>, unique=<span class="hljs-literal">True</span>)
</code></pre>
<p>As I mentioned, I'm more familiar with JavaScript and C# than with Python, and working with the latter to build the Flask API felt like cheating. Certain things like pathing, package handling, and writing workable code were just <em>easy</em>, although I did get hung up on getting the API to correctly parse JSON for the client. I suspect that was more of an issue of my unfamiliarity with the language than anything else, but it did take time to troubleshoot.</p>
<p>To be quite honest, coming from a non-Flask background, I did kind of expect to complete a couple of tutorials and spin up an API without having to do all that much work for it.  </p>
<p>I can't say that it turned out that way, as Python does have its own particulars that require some time to get used to. Still, the Python ecosystem appears to be extremely well organized, and I enjoyed my time building the Flask API.</p>
<p>I've also heard that Django is a better and more scalable option for larger projects. But it seems like it would involve a separate, and steeper, learning curve to become proficient. </p>
<p>Flask was easy enough for me as a non-Python developer to pick up and build something over a weekend. I suspect that learning Django would take quite a bit longer, but with potentially greater dividends over the long run. </p>
<h3 id="heading-pythonflask-resources">Python/Flask Resources</h3>
<p>To build the Flask API, I used:</p>
<ul>
<li><a target="_blank" href="https://www.python.org/">Python 3</a>/<a target="_blank" href="https://pip.pypa.io/en/stable/">pip</a> for package management</li>
<li><a target="_blank" href="https://palletsprojects.com/p/flask/">Flask</a> as the main web framework</li>
<li><a target="_blank" href="https://pypi.org/project/python-dotenv/">python-dotenv</a> to configure environment variables</li>
<li><a target="_blank" href="https://www.sqlite.org/index.html">SQLite</a> as the database </li>
<li><a target="_blank" href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/">Flask-SQLAlchemy</a> as the ORM to work with SQLite</li>
<li><a target="_blank" href="https://flask-migrate.readthedocs.io/en/latest/">Flask-Migrate</a> as an additional tool to migrate data to SQLite </li>
<li><a target="_blank" href="https://flask-cors.readthedocs.io/en/latest/">Flask-CORS</a> to handle the same CORS issue as with the Express API</li>
<li>The <a target="_blank" href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world">Flask Mega-Tutorial</a> to learn the basics</li>
<li>The <a target="_blank" href="https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask">Flask REST API tutorial</a> to understand how to receive HTTP requests</li>
</ul>
<h2 id="heading-c-api-aspnet">C# API: ASP.NET</h2>
<p>I can't tell you how many times I've Googled ".<a target="_blank" href="https://dotnet.microsoft.com/">NET</a>" to understand what it is, how it's different from <a target="_blank" href="https://dotnet.microsoft.com/apps/aspnet">ASP.NET</a>, and why I'd want to use any of it. My C# knowledge comes mainly from working with <a target="_blank" href="https://unity.com/">Unity</a>, which exists somewhat adjacent to .NET and doesn't provide for a lot of exposure to Microsoft's larger ecosystem.</p>
<p>I've spent some time researching <a target="_blank" href="https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&amp;tabs=visual-studio">Razor Pages</a> and <a target="_blank" href="https://docs.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-3.1">MVC</a>, and finally came to understand ASP.NET's breadth of features as Microsoft's open source web framework. I decided to toss ASP.NET into the hat for a potential back end for my app, and set about working through the <a target="_blank" href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-3.1&amp;tabs=visual-studio">official web API tutorial</a> with ASP.NET Core and MongoDB.</p>
<p>The file structure for this version of the API was more complex than the others, given that .NET projects tend to have a much larger footprint:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/ASPNet-Structure.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I should also mention that I already had Visual Studio and all of the required workloads installed, which made the setup process easier. Plus, having spent time with MongoDB for the Express API, I found the database portion of the project to be similar, although by default, ASP.NET seems to prefer using Microsoft's <a target="_blank" href="https://www.microsoft.com/en-us/sql-server/default.aspx">SQL Server</a> and the <a target="_blank" href="https://docs.microsoft.com/en-us/ef/">Entity Framework ORM</a>.</p>
<p>The ASP.NET code for HTTP requests is a bit more complex than what we've seen with the two other APIs, but it's no match for all of the code that sits <em>around</em> it.  </p>
<p>First, consider this snippet in /Controllers/QuestController.cs that handles requests:</p>
<pre><code class="lang-c#"><span class="hljs-keyword">namespace</span> <span class="hljs-title">QuestAPI.Controllers</span>
{
    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"quests/"</span>)</span>]
    [<span class="hljs-meta">ApiController</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QuestsController</span> : <span class="hljs-title">ControllerBase</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> QuestService _questService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">QuestsController</span>(<span class="hljs-params">QuestService questService</span>)</span>
        {
            _questService = questService;
        }

        [<span class="hljs-meta">HttpGet</span>]
        <span class="hljs-keyword">public</span> ActionResult&lt;List&lt;Quest&gt;&gt; Get() =&gt;
            _questService.Get();

        [<span class="hljs-meta">HttpPost</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> ActionResult&lt;Quest&gt; <span class="hljs-title">Create</span>(<span class="hljs-params">Quest quest</span>)</span>
        {
            _questService.Create(quest);
            <span class="hljs-keyword">return</span> CreatedAtRoute(<span class="hljs-string">"GetQuest"</span>, <span class="hljs-keyword">new</span> { id = quest.Id.ToString() }, quest);
        }
    }
}
</code></pre>
<p>Not too terrible, almost kind of readable, in a C# sort of way. The data model in /Models/Quest.cs is even easier:</p>
<pre><code class="lang-c#"><span class="hljs-keyword">namespace</span> <span class="hljs-title">QuestAPI.Models</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Quest</span>
    {
        [<span class="hljs-meta">BsonId</span>]
        [<span class="hljs-meta">BsonRepresentation(BsonType.ObjectId)</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

        [<span class="hljs-meta">BsonElement(<span class="hljs-meta-string">"Name"</span>)</span>]
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Description { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    }
}
</code></pre>
<p>These two snippets essentially do the same things as the previous examples that we've seen: take requests from the front end, process them to get or modify data in the database, and send a response back to the client.  </p>
<p>Yet, as you can probably tell from the complex file structure, there's so much code that surrounds these snippets, along with <a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/">Interfaces</a>, <a target="_blank" href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1">Dependency Injection</a>, and other abstractions, that it can be challenging to understand how it all works together.</p>
<p>Consider the following configuration code in /Startup.cs:</p>
<pre><code class="lang-c#">        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ConfigureServices</span>(<span class="hljs-params">IServiceCollection services</span>)</span>
        {
            services.Configure&lt;QuestDatabaseSettings&gt;(Configuration.GetSection(<span class="hljs-keyword">nameof</span>(QuestDatabaseSettings)));

            services.AddSingleton&lt;IQuestDatabaseSettings&gt;(sp =&gt; sp.GetRequiredService&lt;IOptions&lt;QuestDatabaseSettings&gt;&gt;().Value);

            services.AddSingleton&lt;QuestService&gt;();

            services.AddCors(options =&gt;
            {
                options.AddPolicy(MyAllowSpecificOrigins, builder =&gt;
                {
                    builder.WithOrigins(<span class="hljs-string">"http://localhost:3000/quests"</span>, <span class="hljs-string">"http://localhost:8080"</span>).AllowAnyHeader().AllowAnyMethod();
                });
            });

            services.AddControllers();
        }
</code></pre>
<p>Or this particularly nested bit from a separate <a target="_blank" href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&amp;tabs=visual-studio">SQL Server web API tutorial</a>:</p>
<pre><code class="lang-c#">    [<span class="hljs-meta">HttpGet</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ActionResult&lt;IEnumerable&lt;TodoItemDTO&gt;&gt;&gt; GetTodoItems()
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _context.TodoItems
            .Select(x =&gt; ItemToDTO(x))
            .ToListAsync();
    }
</code></pre>
<p>Lol. What?? As a new user, even familiar as I am with C#, I can go line-by-line to understand each abstraction, or I can just trust that the framework is handling everything for me and forget about it.</p>
<p>I tend to want to know exactly how my code works so that I can fix or alter it if necessary. But I certainly feel like my time spent learning the ins-and-outs of ASP.NET could be better utilized towards mastering another framework.</p>
<p>To be fair, ASP.NET appears to be similar to Django in being more opinionated and providing you with a ton of stuff out of the box, including an authentication solution, database management, and the lot. If these things are important to you, it's certainly worth considering.  </p>
<p>It also has the full support of Microsoft and an open source community. So if you're looking at developing enterprise-level applications that need to scale, you might want to take a longer look at ASP.NET as a potential solution.</p>
<h3 id="heading-caspnet-resources">C#/ASP.Net Resources</h3>
<p>To build the ASP.Net API, I used the following resources:</p>
<ul>
<li><a target="_blank" href="https://visualstudio.microsoft.com/downloads/">Visual Studio Community</a> as my code editor and IDE, with the ASP.NET and web development workload installed (I already had MongoDB running from the Express API)</li>
<li>Microsoft's <a target="_blank" href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-3.1&amp;tabs=visual-studio">official tutorial</a> for building web APIs with ASP.NET and MongoDB</li>
</ul>
<h2 id="heading-tldr">TL;DR</h2>
<p>In all, with some slight variations and hiccups among them, I've gotten each of the web APIs to work with the Vue client, with the ability to view quests from and add quests to the database. Hopefully, my explanation of the process has been helpful in your own search for a back end framework, but here are some additional recommendations just in case:</p>
<ul>
<li>If you're a JavaScript developer and/or want to manage everything that your application does, including its architecture, consider using Express.</li>
<li>If you're a Python developer and/or want a pleasant experience in developing small projects, try Flask, but consider using Django if you need more out-of-the-box support and don't mind conforming to an opinionated framework.</li>
<li>If you're a C# developer and willing to spend the time to learn the most arcane details of C# coding best practices, consider using ASP.NET. Alternatively, if you need enterprise-level support right out of the box, you'd be hard-pressed to find better.</li>
<li>If you don't know what to use and just want to learn back end development, take a look at Flask.  It's easy to work with and will teach you the basics that you'll need to know for building web apps in any coding language.</li>
<li>If you don't know what to use and want an adventure, choose Express. There's a rabbit hole of package management and Stack Overflow questions waiting that may make you tear your hair out, but you'll learn a lot about the JavaScript ecosystem and web development in general.</li>
</ul>
<p>Additionally, two things bear mentioning that threw me for a spin in this process: CORS and environment variables. The former I've mentioned in this article a couple of times already, but it's worth discussing again to understand the scope of building a full stack app on your machine.</p>
<p>Unless you have an integrated development environment that's handling the whole stack for you, you'll likely have a client, a server, and a database that are all running independently of one another.  </p>
<p>In the Express API section above, for example, I was running </p>
<ol>
<li>the Vue CLI server, which rendered my front end app on port 8080; </li>
<li>an NPM script to spin up the Express API server on port 3000; and</li>
<li>a separate instance of the Mongo database to get everything working together. That's three command prompts open and a general mess!</li>
</ol>
<p>If you dig into the Vue code above (or on GitHub), you'll see that the requests made on behalf of the client, running on http://localhost:8080, are to the server on http://localhost:3000, which is where the Express API is listening. This is called "cross-origin resource sharing," or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>, and it's blocked by the browser for security concerns. Most frameworks require you to install an additional package to get the whole thing running in your local environment.</p>
<p>Second, you'll want to become comfortable with <a target="_blank" href="https://en.wikipedia.org/wiki/Environment_variable">environment variables</a>, which can really help smooth some rough pathing edges at runtime. I used <a target="_blank" href="https://www.npmjs.com/package/dotenv">dotenv</a> and <a target="_blank" href="https://pypi.org/project/Flask-Env/">Flask-Env</a> for the Express and Flask projects, respectively. </p>
<p>Both packages allow you to configure things like where your database lives, or what default port your application should be using, in one document. Your application then uses that document at runtime to figure out where to find everything, without any further configuration needed from you.</p>
<p>One final note that may be helpful if you're just working on a back end project and don't want to go through the trouble of building a front end client: consider using a third-party app like <a target="_blank" href="https://www.postman.com/">Postman</a>. I used it to make HTTP requests to each of the APIs to make sure they were working properly before layering on the Vue client and trying to get the whole stack running altogether. </p>
<p>I hope this article has been helpful for you in your own process of looking for a back end framework.  Let me know what you find! </p>
<p>If you enjoyed this article, please consider <a target="_blank" href="https://www.nightpathpub.com/">checking out my games and books</a>, <a target="_blank" href="https://www.youtube.com/msfarzan?sub_confirmation=1">subscribing to my YouTube channel</a>, or <a target="_blank" href="https://discord.gg/RF6k3nB">joining the <em>Entromancy</em> Discord</a>.</p>
<p>M. S. Farzan, Ph.D. has written and worked for high-profile video game companies and editorial websites such as Electronic Arts, Perfect World Entertainment, Modus Games, and MMORPG.com, and has served as the Community Manager for games like <em>Dungeons &amp; Dragons Neverwinter</em> and <em>Mass Effect: Andromeda</em>. He is the Creative Director and Lead Game Designer of <em><a target="_blank" href="https://www.nightpathpub.com/rpg">Entromancy: A Cyberpunk Fantasy RPG</a></em> and author of <em><a target="_blank" href="http://nightpathpub.com/books">The Nightpath Trilogy</a></em>. Find M. S. Farzan on Twitter <a target="_blank" href="https://twitter.com/sominator">@sominator</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How I landed offers from Microsoft, Amazon, and Twitter without an Ivy League degree ]]>
                </title>
                <description>
                    <![CDATA[ By Zhia Chong This is for those of you out there who are about to start your job search and who may be worried that you can’t land a top-tier tech job without a Stanford CS degree. Someone told you that you’re not good enough to get a job at ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-i-landed-offers-from-microsoft-amazon-and-twitter-without-an-ivy-league-degree/</link>
                <guid isPermaLink="false">66d461c857503cc72873deea</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ career advice ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Career development  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ careers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Facebook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Google ]]>
                    </category>
                
                    <category>
                        <![CDATA[ internships ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interviews ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Microsoft ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Twitter ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 23 Feb 2020 08:14:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/02/1_QuyFfwka5D5j7Z2IR4mcCQ.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Zhia Chong</p>
<p>This is for those of you out there who are about to start your job search and who may be worried that you can’t land a top-tier tech job without a Stanford CS degree. Someone told you that you’re not good enough to get a job at Microsoft or Facebook. </p>
<p>But I’m here to tell you that you can get that job. Here’s how I landed my dream job at Twitter.</p>
<p>Read more about my courses <a target="_blank" href="https://docs.google.com/document/d/1PeK69h4H82rwKjhactiE_sAIorCcZgXgXTY7k-nXpnE/edit?usp=sharing">here</a> to learn how I prepared.</p>
<p>You can read about my experiences after a year at Twitter <a target="_blank" href="https://www.freecodecamp.org/news/what-ive-learned-in-1-year-at-twitter-65150f5d4af2/">here</a>.</p>
<h3 id="heading-what-this-article-covers">What this article covers:</h3>
<ul>
<li>My background</li>
<li>How I landed interviews with top tech companies in the world: Facebook Google, Amazon, LinkedIn, Microsoft, Twitter, Pinterest, Snapchat, and others.</li>
<li>How I landed multiple offers as a full-time software engineer</li>
<li>Lessons from my interview experience</li>
<li>Subscribe <a target="_blank" href="http://eepurl.com/dnt9Sf">here</a> for more article updates from me</li>
</ul>
<p>If you prefer to watch my story instead, I made a video here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/83Reyvrs-VQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-background">Background</h2>
<p>I did not graduate from an Ivy league school. I went to a community college in Idaho for two years, and then finished my CS degree at a small Catholic university.</p>
<p>I started learning computer science in my junior year of college, because it sounded fun to me at the time. The only thing resembling a computer I had growing up was a Chinese copycat of the Nintendo SNES. Even then, it would break every time I put a cartridge in it.</p>
<p>To support myself through college, I took multiple part-time jobs like cleaning floors and working stand-up concessions.</p>
<p>When I graduated, I didn’t have a job lined up. I applied to as many big tech companies as I could, and had the good fortune of landing a few phone interviews.</p>
<p>At this point, I didn’t have a single notion of what a technical screen would be like, much less how to prepare for it. I headed into these interviews thinking that the interviewer would ask me what a linked list or binary tree was.</p>
<p>I <strong>didn’t pass</strong> any of those interviews.</p>
<h2 id="heading-moving-forward">Moving forward</h2>
<p>I didn’t delve too much into whether I was good. I knew that I could learn things fast. I just needed an opportunity.</p>
<p>As the saying goes, cast your net far and wide. So that’s what I did.</p>
<p>What I did next is something I’m particularly proud of. I wrote a simple Python script that scraped job listings on Craigslist with titles containing keywords from a list, and collected the emails in a spreadsheet. For the actual war story, you can read the article <a target="_blank" href="https://www.freecodecamp.org/news/how-i-built-a-web-crawler-to-automate-my-job-search-f825fb5af718/">here</a>.</p>
<p>It wasn’t the smartest solution, but people who post on Craigslist are surprisingly accurate with their titles.</p>
<p>Craigslist, however, didn’t like people scraping their website. To work around this, I ran my script through a VPN, and had a timer that would pause the script every few minutes or so. It wasn’t perfect, but it worked well enough.</p>
<p>In the end I collected about 500 emails from around San Francisco, Portland, Spokane, and Seattle. I filtered the results by how specific and recent they were, and kept improving it by adding more and more features.</p>
<p>As it turned out, there were a few bots in the market already that crawled Craigslist and sent out automated emails. These were mostly offshore companies that were looking to pitch their company to the US market.</p>
<p>One of my workarounds was that I crafted emails that used keywords from their listings in the title of my emails. I then added more details using the body of the postings to make it seem more personable. I did a quick A/B test, and the replies I received had increased quite a bit from around 2–3% to 10%.</p>
<p>Out of the 500 or so emails, I received about 50 replies, and landed phone screens with a small percentage of those. I stopped at 500 because I was short on time and needed to finalize a job as soon as possible. I was optimizing for results rather than reach at that point.</p>
<p>As luck would have it, I finally landed a job at a startup in Seattle as a junior software engineer. The startup was located in Kirkland at the time, so I had to take a 45-min bus ride to make it in time for the interview.</p>
<p>I then stayed there for the next 3.5 years, where I learned a great deal of stuff like Amazon AWS, EC2, DynamoDB, SQS, and Docker. I grew a lot during this period. I learned how to write modular, maintainable code. I learned how to reason about software design. And I learned how to handle people problems.</p>
<p>I was working next to a group of smart people who held jobs at Microsoft, Amazon, and LinkedIn, and I tried to be the “sponge” in the group. I absorbed anything and everything they threw at me. I believe this made a huge impact in my career.</p>
<h2 id="heading-startup-days">Startup Days</h2>
<p>During my stint at the startup, I worked almost exclusively on backend development, with some dev-ops in between. I started out writing some functions to add/modify a feature that were mostly small in scope. But it was a great opportunity to understand the codebase and get some code reviews.</p>
<p>A year into it, I started owning parts of the codebase, and then I was tasked with turning a set of features into a service. That was the start of the SOA phase for the startup. We started turning various components of the site into services, and that’s how I started learning more about RESTful services, authentication, AWS services, pub-sub, distributed systems and so forth.</p>
<p>The interesting part here is that <em>I didn’t learn about any of these through books or formal education.</em> Rather, I needed to get that set of features done and there were the bottlenecks.</p>
<p>So I thought, let’s go solve it!</p>
<p>There were many times where I was stuck in analysis paralysis — a state where I over-analyzed scenarios and ended up not able to make progress.</p>
<p>Those trying times were the <strong>greatest</strong> learning opportunities. I started to learn feature scoping, negotiations, monitoring, alerting, and documentation. Each step of the process revealed more things I needed to learn. I grew the most during these 2–3 years, both as an individual and software engineer.</p>
<h2 id="heading-how-i-prepared-for-my-interviews">How I prepared for my interviews</h2>
<p>After suffering through my first job search, I told myself that I must be prepared in future interviews.</p>
<p>I started preparing for interviews by charting out an overview of what I was good at, bad at, and where I could improve. I broke it down into three categories: <strong>data structures, algorithms, and system design.</strong></p>
<p>Having worked in PHP for most of my professional career, and C++ in college, I wanted to try something a little simpler and less verbose for interviewing.</p>
<p>For this reason, I picked Python. It is a great language to learn, easy to pick up, supports many data structures out of the box, and can be written quickly on the whiteboard. I learned Python by going through YouTube tutorials like <a target="_blank" href="https://www.youtube.com/watch?v=Z1Yd7upQsXY">these</a>, and also reading their documentation. I prefer Python 2.x, but you can go for either 2.x or 3.</p>
<p>Also, another reason why I picked Python is that it’s highly readable and easy to write on a whiteboard. Here’s a trivial comparison between C++ and Python.</p>
<p>A C++ program to sort in descending order:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;bits/stdc++.h&gt;</span></span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>; 
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{   
    <span class="hljs-keyword">int</span> arr[] = {<span class="hljs-number">1</span>,<span class="hljs-number">10</span>,<span class="hljs-number">0</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>};
    <span class="hljs-keyword">int</span> n = size(arr)/<span class="hljs-keyword">sizeof</span>(arr[<span class="hljs-number">0</span>]);   
    sort(arr, arr + n, greater&lt;<span class="hljs-keyword">int</span>&gt;());   
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; n; i++) {       
        <span class="hljs-built_in">cout</span> &lt;&lt; arr[i] &lt;&lt; <span class="hljs-string">" "</span>;   
    }    
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Compare that with Python’s version:</p>
<pre><code class="lang-py">a = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">1000</span>]
a.sort(reverse=<span class="hljs-literal">True</span>)
<span class="hljs-keyword">print</span> a
</code></pre>
<p>I’ve received feedback from interviewers to <strong>err on the side of brevity</strong> in an interview. In a 45-minute interview, you want to use most of your time solving the actual problem.</p>
<p>Pro tip: pick a language that’s less verbose so that you can write the code more quickly on the whiteboard.</p>
<h2 id="heading-preparation-mode">Preparation mode</h2>
<p>I spent about a week going through simple challenges on LeetCode, HackerRank, and Project Euler to familiarize myself with their interfaces, and to get used to writing code in Python.</p>
<p>The first week gave me insights into my competence level at certain programming languages. I spent another week going through some design challenges like “design X” and went as wide and deep as I could.</p>
<p>This was a lot of fun for me, because I often looked at iOS apps and tried to figure out how they did it. For example, how would you build Instagram from scratch? (I was asked this at Facebook.)</p>
<p>My background is in API designs and service-oriented architecture, so I took this opportunity to show how I would design my own version of Instagram. And because I have some iOS programming experience from my side-projects, I could talk a little bit about callbacks and push/long-polls here.</p>
<p>I started the conversation with some features I’d like to have on my own version of Instagram: likes, upload a photo, and a simple timeline. Feature scoping enabled me to build a very solid API because I know these scenarios well.</p>
<p>I then drew some pictures of a high-level design, of how the client would interact with the backend, and of how the backend would store the data.</p>
<p>I started small, and then added more components where needed and proactively sought where the bottlenecks were. I made educated guesses (read <strong>educated, not blind guesses</strong>) on what the requirements would be, and how each technology would fit in well. And also equally important, what technologies would <em>not fit well.</em></p>
<p>For example, why would you use Cassandra over MySQL to store certain information (hint: scale, speed of development, schema reviews), why use OAuth over simple authentication, Redis vs Memcached for caching data, streaming vs batch processing, and so on.</p>
<p>There are many areas you can explore here, so typically a one-hour session is not enough. To do well on these questions, you have to read and learn about trade-offs. Pros and cons of technologies in the industry. For this, I recommend a site like <a target="_blank" href="http://highscalability.com/all-time-favorites/">HighScalability</a>.</p>
<p>Take it like a typical brainstorming session with a coworker, so explore <em>as widely and as deeply</em> as you can.</p>
<p>It’s crucial to know that these design interviews are meant to explore how much you know and how well you know it, and it’s <strong>an opportunity for you to shine.</strong> I watched this YouTube <a target="_blank" href="https://www.youtube.com/watch?v=ZgdS0EUmn70">video</a> from an ex-Facebook engineer about how to solve design problems, and it gave me insights that helped me tremendously with my design interviews. My two main lessons from it: <strong>drive the design conversation,</strong> and <strong>show what you know</strong>.</p>
<p>I listed out my competency level for: <strong>data structures</strong> (linked list, hash map, binary tree, binary search tree, heap, array), <strong>algorithms</strong> (binary search, hashing, dynamic programming, sorting), and <strong>language-specific syntax and libraries</strong> (like sort, lambda for Python, appending, indexing).</p>
<p>I picked the area I was worst at, and started working on it: <strong>algorithms</strong>.</p>
<p>Algorithms have never been my forte. It’s been a while since my college days, and I didn’t spend much time doing binary search in my day-to-day career. I had an inkling of how each algorithm would perform, and in what scenarios to use them. But I wasn’t 100% comfortable with writing a binary search in under 10 mins. On a whiteboard. In front of an interviewer.</p>
<p>I also picked up a bunch of fine-point markers from <a target="_blank" href="https://www.amazon.com/86601-Low-Odor-Markers-Assorted-8-Count/dp/B000Z88D2E/ref=sr_1_3?ie=UTF8&amp;qid=1518801079&amp;sr=8-3&amp;keywords=white+board+pens">Amazon</a>, which work amazingly well. Perhaps it’s just me, but the fine-point markers in interviewing rooms usually don’t work at all. I’d usually scramble for 2–3 mins looking for a working pen, and that’s 2–3 mins you can’t afford to waste. Plus, fine-point markers allow you to write 5–8 more lines of code on a typical whiteboard vs. thicker ones. :)</p>
<p>Pro tip: Get your own set of fine-point markers.</p>
<p>I got a whiteboard from Costco for $50, some books from Amazon (listed in the tools I recommend section below), and started practicing. I made sure I ramped up on binary search, recursion, dynamic programming, BFS and DFS. A lot of interviewing questions revolved around recursion and binary search or some variations of it.</p>
<p>The best interviewing questions I’ve seen had many different solutions to them, and there’s an additional layer added on top as you progress through.</p>
<p>One Google question I had was related to file-system directories, and how to traverse them (hint: recursion). I solved that relatively quickly, and the interviewer asked how to identify a missing file in that directory. That was a little more difficult, but I got through it. And we then moved into how to rebuild the directory, how to serialize/deserialize it, and we spent a good chunk of time debating how file directories work underneath the hood. It was a very enjoyable session for me.</p>
<h2 id="heading-interviewing-at-top-tier-companies">Interviewing at top-tier companies</h2>
<p>It was a nerve-wracking experience, to say the least, and a real roller-coaster.</p>
<p>I allocated my time in the following manner: 20% resume, 20% research and 60% interview preparation.</p>
<p>I spent 20% of my time fixing up my resume, which hadn’t been updated in at least three years. I took a hard look at the stuff I’ve done in the past, and picked projects I handled end-to-end, <strong>regardless of complexity.</strong></p>
<p>The reason for doing this is two-fold. Taking a project from start to completion demands discipline and leadership — two of the traits I’d like to be identified with.</p>
<p>Secondly, ownership of a project end-to-end means I can talk about each aspect of the project <strong>at length and in depth.</strong> This proved critical in helping me navigate my design round at Twitter, where they grilled me hard on not only the designs of my projects, but also the decisions behind them.</p>
<p>20% of my time was used for research. Research in this case meant doing due diligence on companies I was interested in and reaching out for referrals. Having referrals helps with return calls.</p>
<p>From my experience, I sent out 20 or so cold messages to startups and mid-stage companies, and only heard back from a handful. But, almost all the companies I was referred to by an existing employee sent me a message within a week. This is anecdotal, but there’s value to be had there.</p>
<p>I am not that sociable, and I didn’t know many people who’d be able to refer me to a company I was interested in. To solve that problem, I went on LinkedIn. They have a search functionality that I used to search for 1st and 2nd-level connections. 2nd-level connections are people who’re one hop away from your immediate circle. In other words, we have mutual friends who can <strong>vouch for my credibility</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/linkedin-search.png" alt="Image" width="600" height="400" loading="lazy">
<em>LinkedIn search</em></p>
<p>This is incredibly important, because cold-calling someone for a job is very, very hard, especially in today’s market. People tend to err on the side of caution when it comes to cold-callers. Using LinkedIn was super helpful for my research phase.</p>
<p>Looking back at all the companies I interviewed at, here are my thoughts on each of them:</p>
<ul>
<li><strong>Facebook/Google</strong> — very mechanical. The standard interviewing process, and I didn’t feel any personal connection to them.</li>
<li><strong>Pinterest</strong> — not the best interviewing experience, but a cool product and company.</li>
<li><strong>Microsoft</strong> — loved the team and especially the manager and her manager. Standard interviewing questions, but very personable. Close-second choice. Your mileage may vary, though — each team at Microsoft interviews differently.</li>
<li><strong>Amazon</strong> — standard interviewing process. About 50% of the people love it, the others don’t.</li>
<li><strong>Twitter</strong> — incredibly fun and personal. Loved the interviewing process, gave a lot of emphasis on the individual and what I’d done in the past.</li>
<li><strong>Snapchat</strong> — cool office in LA, great bunch of people who decided to jump on the startup bandwagon. Felt like things were shrouded under a cloud of secrecy.</li>
<li><strong>Lyft</strong> — near to where I live, nice office, standard interviewing process. No strong feelings about it.</li>
</ul>
<h2 id="heading-lets-talk-about-my-favorite">Let’s talk about my favorite</h2>
<p>In many ways, I’d say Twitter’s interviewing style was hard. But at the same time, it was more interesting and personable than other companies I’ve interviewed at.</p>
<p>Their interviewing process starts with an introductory phone call with an engineering manager. That’s followed up by one or two technical phone screens, depending on how you perform. If you do well, they’ll fly you out to the office you’re interviewing for, which was Seattle in my case. There are three 1-hour-and-15-minute rounds, each with two interviewers.</p>
<p>The first two technical phone screens are the standard, run-of-the-mill technical screens where you solve coding problems on a shared coding doc.</p>
<p>The onsite rounds, however, are much more conversational and feel much less intimidating. The interviewers will ask you in-depth questions about your past projects, and they’ll grill you on what you’ve done in the past. If you claim ownership of a project, you should expect some questions about it. You’re encouraged to use them for references and to bounce ideas off of.</p>
<p>I never felt any pressure to magically come up with a fully working solution, and it felt highly collaborative.</p>
<h2 id="heading-the-others">The others</h2>
<p>In comparison, interviewing at Facebook and Google felt much more mechanical. They have one or two technical phone screens, and five to six onsite coding rounds. Each round involves some coding on a whiteboard, and you’re expected to come up with a near-perfect solution in a reasonable amount of time.</p>
<p>Facebook has two coding rounds, one design round, and one behavioral round.</p>
<p>I went through an additional shadow round at the end of the day, which didn’t count towards my overall score.</p>
<p>Google had five coding rounds, none of which focused on designs, and not a single interviewer asked about my previous projects. I don’t necessarily think this is bad. But I think it felt very mechanical and didn’t give much opportunity for the engineer to show what they’re capable of. Some people do well in these scenarios, much like some students do well in exams.</p>
<p>I <strong>did not enjoy</strong> my interview with Pinterest. I think the product itself is interesting, and their engineering team seems to be working on very cool technical <a target="_blank" href="https://medium.com/@Pinterest_Engineering">problems</a>. But I definitely had a negative experience during my interview there.</p>
<p>Pinterest has three coding rounds and one design round. Of those four rounds, the design round was most disappointing to me. Here’s why:</p>
<p>The interviewer came in late, and he spent a few minutes glancing over my resume before proceeding to draw some APIs on the board. He gave a short description of what he expected the API to do, and asked how I would solve it. We clarified the features of the API, and I started describing my solution using the whiteboard. About 5 minutes into it, I turned around and <strong>saw him taking a nap!</strong></p>
<p>Not cool.</p>
<p>I gave the recruiter my feedback in a survey, and I didn’t hear back from them after that.</p>
<p>I won’t delve into specifics of the questions I was asked during all the interviews. Instead, I’ll share some of the insights and useful tips I learned from my preparation process.</p>
<h2 id="heading-what-i-learned">What I learned:</h2>
<ul>
<li>Be <strong>honest</strong> on your resume. Most companies <em>will</em> ask you questions about your resume, and they can tell if you made it up. It’s better to be able to know <strong>100% about one project than to know 10% about 10 different projects.</strong></li>
<li>One-page resumes are <strong>recommended</strong>. This is especially true for tech companies, and it seems that the wisdom within the tech sphere is that you should reserve two pages and longer for post-doctoral work, or if you’ve done a lot of projects that you know and care deeply about. A friend of mine runs a <a target="_blank" href="https://www.jobscan.co/">company called Jobscan</a> that scans resumes and makes <em>specific, actionable</em> improvements on them. They’re pretty awesome, so try them out :)</li>
<li><strong>Socialize and establish a network</strong>. There’s a lot of competition for software engineering jobs, and these top tech companies are filtering through thousands of resumes a day. Having a referral will help you get some eyes on your resume.</li>
<li><strong>Nail</strong> your pitch. Every company that’s interested in you wants to know why you’re interested in them. <strong>A bad answer</strong>: I just need a job right now to pay bills. <strong>A less-bad answer</strong>: I was browsing online and found you guys. Sounds like you’re working on interesting things. <strong>A good answer</strong>: I know you’re doing some interesting work in X to achieve Y. I’ve done some work in the past and here’s what I learned about A, B, C that might be related to X. I am passionate about Y because blah. (<em>Don’t</em> use this as a template. Instead, you should see the pattern here — do your research, use your background, and show the company why both of you would fit well together.)</li>
</ul>
<h2 id="heading-some-more-advice">Some more advice</h2>
<p>Technical interviews are incredibly difficult, and sometimes it’s a hit-or-miss. The best opportunities, however, are reserved for those <em>who are prepared.</em></p>
<ul>
<li><strong>Prepare early, prepare <em>well</em></strong>. Everyone knows that they should prepare for an interview, but most don’t know how to do it <em>well</em>. As with anything worth doing, it takes deliberate practice to do well at something. And deliberate practice means you need to have a system.</li>
<li><strong>Build a system</strong> to practice technical skills. I started by rating myself from 1–10 on how good I was, and worked on the ones I was worst at. I spent days on different types of questions until I fully mastered each concept. And I <strong>wrote notes daily on Evernote</strong>. I had a note that serves as a brain dump for all things programming. It is full of programming tips &amp; tricks, common errors and misconceptions, frameworks for solving specific types of questions, and much more.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/my-notebook.png" alt="Image" width="600" height="400" loading="lazy">
<em>My notebook</em></p>
<ul>
<li><strong>Keep a notebook</strong> of the things you’ve learned. I use both <a target="_blank" href="http://evernote.com">Evernote</a> and <a target="_blank" href="http://onenote.com">OneNote</a> to keep track of things. OneNote for technical stuff/code, because I like that I can easily format the note any way I like. I use Evernote for essays/thoughts. The image above shows a note I keep on architecture and system designs.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/02/evernote.png" alt="Image" width="600" height="400" loading="lazy">
<em>Evernote for thoughts/tips</em></p>
<ul>
<li><strong>Jot everything down</strong>, even if you don’t think you’ll use it. I tend to forget very easily, so anything that I learn I write it down, including shell commands. I read technical blogs from time-to-time, and if I find anything interesting I jot it down on Evernote right away. I’ll revise it every week or month and reorganize accordingly. This has helped me tremendously over my career.</li>
<li><strong>Get mock interviews</strong>. This was definitely very valuable and I highly advise it. I had mock interviews with friends and tried to practice as much as I could. If you can’t find friends to practice with, then I recommend Refdash, which is an Interview-As-A-Service. They have a group of interviewers who work at big tech companies like Google, Facebook, and Microsoft. These interviewers will assess you on your coding and design skills. The best part of it is they’ll give you a score at the end of it with specific actionable items on how to improve.</li>
<li>It’s <strong>OK to fail. I failed multiple interviews during this whole process.</strong> Sometimes you just have a bad day. It’s not the end of the world if you fail. Companies are biased towards saying no because it’s a lower risk for them. A false positive costs more than a false negative in the long run. The first few rejections definitely stung the most. I failed multiple phone screens when I first started interviewing, and my confidence level sunk. I had doubts in my mind about my abilities and started fearing that my skills weren’t relevant in today’s job market. However, I gave myself a tip: If you fail 10 times, then try 10 times more. <em>All you need is one success.</em> That reassurance gave me a lot of confidence to keep pushing through and when my first offer came through, the other offers came much more easily.</li>
</ul>
<p>It took me about <strong>2 months</strong> of deliberate practice and preparation for my interviews. I spent about <strong>20 hours/week, or 80 hours/month,</strong> learning and writing notes on top of a full time job.</p>
<p>To build up my resume, it took 3.5 years of focused, deliberate work. I intentionally picked things that were tough and icky so that I could learn more than anyone else. Even though I don’t have a brand name university or top-tier tech company on my resume, I made up for it with a clear, thorough understanding of the projects I worked on. And this was possible because I researched and wrote down notes of everything I learned, and have a system to review them.</p>
<p>Remember: the strong survives, the tough thrives.</p>
<p>TL;DR: Don’t give up, set yourself up for opportunities, practice a lot, and stay hopeful. Focus on the process, and take a disciplined, dedicated approach to the process.</p>
<h3 id="heading-tools-i-recommend">Tools I Recommend</h3>
<ul>
<li><a target="_blank" href="https://amzn.to/2I80wup">Designing Data-Intensive Applications</a>: Awesome book for learning about scaling distributed systems! Highly recommended.</li>
<li><a target="_blank" href="http://amzn.to/2Dcs6Qd">Elements of Programming Interviews</a>: Great for solving coding problems.</li>
<li><a target="_blank" href="http://amzn.to/2Hj91OH">Cracking The Coding Interview</a>: Great for covering foundational CS coding problems.</li>
<li><a target="_blank" href="https://www.dailycodingproblem.com/zhiachong">Daily Coding Problem.com</a>: This is a free-to-try website that offers free daily coding problems. You can sign up for interesting daily coding challenges, and you can pay for solutions if you want.</li>
<li><a target="_blank" href="https://db.tt/tdUSP79S">Dropbox</a>: I keep all my files, pictures, resume here. Easy access, installed once and available everywhere. Love it ❤️ (If you sign up thru this link, both of us will get free 500MB!</li>
<li><a target="_blank" href="https://coderunnerapp.com/">CodeRunner</a>: I love this Mac app! I used this multiple times to run ad-hoc Python scripts/functions and it just works amazingly well. ?</li>
<li><a target="_blank" href="https://amzn.to/2D8FUxS">Kafka the Guide</a>: I used this book as a reference guide, and enjoyed it for the high-level description.</li>
</ul>
<p>(I share more resources I personally have used and recommend on <a target="_blank" href="http://zhiachong.com/resources">zhiachong.com</a>, if you’re interested in learning more.)</p>
<p>Thanks for reading my story! You can find me on <a target="_blank" href="https://twitter.com/zhiachong">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/zhiachong/">LinkedIn</a>. I would love to connect and talk more about tech, startups, travel :D</p>
<p><strong>Credits:</strong></p>
<p><a target="_blank" href="https://twitter.com/hakczar">Brandon O’brien</a>, my mentor and good friend, for proof-reading and providing valuable feedback on how to improve this article.</p>
<p><a target="_blank" href="https://medium.com/@yksugi">YK Sugishita</a>, an up-and-coming Youtube star who left his job at Google to pursue his dreams, for proof-reading and giving critical feedback.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Complete Back End System with Serverless ]]>
                </title>
                <description>
                    <![CDATA[ By Sam Williams This article will teach you how to build and deploy everything you need to be able to build a back-end for your application. We'll be using AWS to host all of this and deploying it all using the Serverless Framework. By the end of thi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/complete-back-end-system-with-serverless/</link>
                <guid isPermaLink="false">66d460d1c7632f8bfbf1e49b</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ serverless ]]>
                    </category>
                
                    <category>
                        <![CDATA[ serverless framework ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 27 Dec 2019 09:33:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/thumbnail.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sam Williams</p>
<p>This article will teach you how to build and deploy everything you need to be able to build a back-end for your application. We'll be using AWS to host all of this and deploying it all using the Serverless Framework.</p>
<p>By the end of this article you'll know how to:</p>
<ul>
<li><a class="post-section-overview" href="#">Set up your AWS account to work with the Serverless Framework</a></li>
<li><a class="post-section-overview" href="#">Set up a Serverless Project and deploy a Lambda</a></li>
<li><a class="post-section-overview" href="#">Create private cloud storage with S3 bucket and upload files from your computer</a></li>
<li><a class="post-section-overview" href="#">Deploy an API using API Gateway and AWS Lambda</a></li>
<li><a class="post-section-overview" href="#">Create a serverless database table with AWS DynamoDB</a></li>
<li><a class="post-section-overview" href="#">Create an API to get data from your DynamoDB table</a></li>
<li><a class="post-section-overview" href="#">Create an API to add data to your DynamoDB table</a></li>
<li><a class="post-section-overview" href="#">Create APIs to store files and get files from your S3 bucket</a></li>
<li><a class="post-section-overview" href="#">Secure all of your API endpoints with API keys</a></li>
</ul>
<p>Being able to do all these things gives you the ability to create all the functionality needed from most application back ends.</p>
<p><a class="anchor" id="setup"></a></p>
<h1 id="heading-serverless-setup-with-aws"><strong>Serverless Setup with AWS</strong></h1>
<p>The Serverless Framework is a tool that we can use as developers to configure and deploy services from our computers. There's a bit of setup to allow all of this to work together and this section will show you how to do that.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/videoseries?list=PLmexTtcbIn_gP8bpsUsHfv-58KsKPsGEo">Embedded content</a></p>
<p>To allow Serverless to do work on your account, you need to set up a user for it. To do this, navigate into AWS and search for "IAM" (Identity and Access Management).</p>
<p>Once on the IAM Page, click on <em>Users</em> in the list on the left hand side. This will open the list of users on your account. From here we'll be clicking <em>Add user.</em></p>
<p>We need to create a user which has <em>Programmatic access</em> and I've called my user <em>ServerlessAccount</em>, but the name doesn't matter too much.</p>
<p><img src="https://completecoding.io/content/images/2019/08/createUser-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next, we need to give the user some permissions. When on the permissions screen, select <em>Attach existing policies directly</em> and then select <em>AdministratorAccess</em>. This will give the Serverless Framework permission to create all the resources it needs to.</p>
<p>We don't need to add any tags, so we can move straight onto <em>Review</em>.</p>
<p><img src="https://completecoding.io/content/images/2019/08/credential.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On the review window, you'll see the user has been given an <em>Access key ID</em> and a <em>Secret access key</em>. We'll be needing those in the next part so keep this page open.</p>
<h3 id="heading-serverless-install-and-configuration"><strong>Serverless Install and Configuration</strong></h3>
<p>Now that we've created our user, we need to install the Serverless Framework on our machine.</p>
<p>Open up a terminal and run this command to install Serverless globally on your computer. If you haven't got NodeJS installed check out <a target="_blank" href="https://nodejs.org/en/download/">this page.</a></p>
<pre><code>npm install -g serverless
</code></pre><p>Now that we've got Serverless installed, we need to set up the credentials for Serverless to use. Run this command, putting your <em>access key ID</em> and <em>Secret access key</em> in the correct places:</p>
<pre><code class="lang-js">serverless config credentials --provider aws --key ${Your access key ID} --secret ${Your secret access key} --profile serverlessUser
</code></pre>
<p>Once this has been run, you're all set up with Serverless.</p>
<p><a class="anchor" id="firstlambda"></a></p>
<h1 id="heading-deploying-your-first-aws-lambda"><strong>Deploying Your First AWS Lambda</strong></h1>
<p>With out serverlessUser set up, we want to deploy something using the Serverless Framework. We can use Serverless templates to setup a basic project that we can deploy. This will be the base for the whole of this Serverless project.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/sku9Rrci-tE?feature=oembed">Embedded content</a></p>
<p>In your terminal we can create a Serverless project from a template. This command will create a NodeJS Serverless project in the <code>myServerlessProject</code> folder:</p>
<pre><code>serverless create --template aws-nodejs --path myServerlessProject
</code></pre><p>If you now open the folder up in your code editor we can look at what we've created.</p>
<p><img src="https://completecoding.io/content/images/2019/12/folderStruct.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We've got two file worth talking about: <code>handler.js</code> and <code>serverless.yml</code></p>
<h3 id="heading-handlerjs"><strong>handler.js</strong></h3>
<p>This file is a function that will be uploaded as a Lambda function to your AWS account. Lambda functions are great and we'll use a lot more of them later on in the series.</p>
<h3 id="heading-serverlessyml"><strong>serverless.yml</strong></h3>
<p>This is a very important file for us. This is where all the configuration for our deployment goes. It tells Serverless what runtime to use, which account to deploy to, and what to deploy.</p>
<p>We need to make a change to this file so that our deployment works properly. In the <code>provider</code> object we need to add a new line of <code>profile: serverlessUser</code>. This tells Serverless to use the AWS credentials we created in the last section.</p>
<p>We can scroll down to <code>functions</code> and see that we have one function which is called <code>hello</code> and points to the function within the <code>handler.js</code> file. This means we will be deploying this Lambda function as part of this project.</p>
<p>We'll learn a lot more about this <code>serverless.yml</code> file later on in this article.</p>
<h2 id="heading-deploying-our-project"><strong>Deploying Our Project</strong></h2>
<p>Now that we've looked at the files it's time to do our first deployment. Open up a terminal and navigate to our project folder. Deploying is as simple as typing:</p>
<pre><code>serverless deploy
</code></pre><p>This takes a while, but when it's done we can check that everything has deployed successfully.</p>
<p>Open up your browser and navigate to your AWS account. Search for <code>Lambda</code> and you'll see a list of all your Lambda functions. (If you don't see any then check that your region is set to <code>N. Virginia</code>). You should see the <code>myserverlessproject-dev-hello</code> Lambda which contains the exact code that is in the <code>handler.js</code> file in your project folder.</p>
<p><a class="anchor" id="s3"></a></p>
<h1 id="heading-deploying-an-s3-bucket-and-uploading-files"><strong>Deploying an S3 Bucket and Uploading Files</strong></h1>
<p>In this section we're going to learn how we can deploy an Amazon S3 bucket and then sync up files from our computer. This is how we can start using S3 as cloud storage for our files.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/8dc72i41r1A?feature=oembed">Embedded content</a></p>
<p>Open up the <code>serverless.yml</code> file and remove all the commented out lines. Scroll to the bottom of the file and add the following code to include our S3 resources:</p>
<pre><code>resources:
    Resources:
        DemoBucketUpload:
            Type: AWS::S3::Bucket
            <span class="hljs-attr">Properties</span>:
                BucketName: EnterAUniqueBucketNameHere
</code></pre><p>Change the name of the bucket and we're ready to deploy again. Open up your terminal again and run <code>serverless deploy</code>. You may get an error saying that the bucket name is not unique, in which case you'll need to change the bucket name, save the file and rerun the command.</p>
<p>If it is successful we can then go and see our new S3 bucket in our AWS Console through our browser. Search for <code>S3</code> and then you should see your newly created bucket.</p>
<h2 id="heading-syncing-up-your-files"><strong>Syncing up your files</strong></h2>
<p>Having a bucket is great, but now we need to put files in the bucket. We're going to be using a Serverless plugin called S3 Sync to do this for us. To add this plugin to our project we need to define the plugins. After your provider object, add this code:</p>
<pre><code>plugins:
    - serverless-s3-sync
</code></pre><p>This plugin also needs some custom configuration, so we add another field to our <code>serverless.yml</code> file, changing out the bucket name for yours:</p>
<pre><code>custom:
    s3Sync:
        - bucketName: YourUniqueBucketName
          <span class="hljs-attr">localDir</span>: UploadData
</code></pre><p>This section of code is telling the S3 Sync plugin to upload the contents of the <code>UploadData</code> folder to our bucket. We don't currently have that folder so we need to create it and add some files. You can add a text file, an image, or whatever you want to be uploaded, just make sure there is at least 1 file in the folder.</p>
<p>The last thing we need to do is to install the plugin. Luckily, all Serverless plugins are also npm packages, so we can install it by running <code>npm install --save-dev serverless-s3-sync</code> in our terminal.</p>
<p>As we've done before, we can now run <code>serverless deploy</code> and wait for the deployment to complete. Once it is complete we can go back into our browser and into our bucket and we should see all the files that we put in the <code>UploadData</code> folder in our project.</p>
<p><img src="https://completecoding.io/content/images/2019/12/Screenshot-2019-12-10-at-07.12.07.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a class="anchor" id="api"></a></p>
<h1 id="heading-creating-an-api-with-lambda-and-api-gateway"><strong>Creating an API with Lambda and API Gateway</strong></h1>
<p>In this section we'll learn to do one of the most useful things with Serverless: create an API. Creating an API allows you to do so many things, from getting data from databases, S3 storage, hitting other APIs, and much more!</p>
<p><a target="_blank" href="https://www.youtube.com/embed/Jruqo0KVOWk?feature=oembed">Embedded content</a></p>
<p>To create the API we first need to create a new Lambda function to handle the request. We're going to make a few Lambdas, so we're going to create a <code>lambdas</code> folder in our project with two subfolders, <code>common</code> and <code>endpoints</code>.</p>
<p><img src="https://completecoding.io/content/images/2019/12/Screenshot-2019-12-10-at-07.47.27.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Inside the endpoints folder we can add a new file called <code>getUser.js</code>. This API is going to allow someone to make a request and get back data based on the ID of a user. This is the code for the API:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Responses = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/API_Responses'</span>);

<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> event =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event'</span>, event);

    <span class="hljs-keyword">if</span> (!event.pathParameters || !event.pathParameters.ID) {
        <span class="hljs-comment">// failed without an ID</span>
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'missing the ID from the path'</span> });
    }

    <span class="hljs-keyword">let</span> ID = event.pathParameters.ID;

    <span class="hljs-keyword">if</span> (data[ID]) {
        <span class="hljs-comment">// return the data</span>
        <span class="hljs-keyword">return</span> Responses._200(data[ID]);
    }

    <span class="hljs-comment">//failed as ID not in the data</span>
    <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'no ID in data'</span> });
};

<span class="hljs-keyword">const</span> data = {
    <span class="hljs-number">1234</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">'Anna Jones'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>, <span class="hljs-attr">job</span>: <span class="hljs-string">'journalist'</span> },
    <span class="hljs-number">7893</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">'Chris Smith'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">52</span>, <span class="hljs-attr">job</span>: <span class="hljs-string">'teacher'</span> },
    <span class="hljs-number">5132</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">'Tom Hague'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span>, <span class="hljs-attr">job</span>: <span class="hljs-string">'plasterer'</span> },
};
</code></pre>
<p>If the request doesn't contain an ID then we return a failed response. If there is data for that ID then we return that data. If there isn't data for that user ID then we also return a failure response.</p>
<p>As you may have noticed we are requiring in the <code>Responses</code> object from <code>API_Responses</code>. These responses are going to be common to every API that we make, so making this code importable is a smart move. Create a new file called <code>API_Responses.js</code> in the <code>common</code> folder and add this code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Responses = {
    _200(data = {}) {
        <span class="hljs-keyword">return</span> {
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
                <span class="hljs-string">'Access-Control-Allow-Methods'</span>: <span class="hljs-string">'*'</span>,
                <span class="hljs-string">'Access-Control-Allow-Origin'</span>: <span class="hljs-string">'*'</span>,
            },
            <span class="hljs-attr">statusCode</span>: <span class="hljs-number">200</span>,
            <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data),
        };
    },

    _400(data = {}) {
        <span class="hljs-keyword">return</span> {
            <span class="hljs-attr">headers</span>: {
                <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
                <span class="hljs-string">'Access-Control-Allow-Methods'</span>: <span class="hljs-string">'*'</span>,
                <span class="hljs-string">'Access-Control-Allow-Origin'</span>: <span class="hljs-string">'*'</span>,
            },
            <span class="hljs-attr">statusCode</span>: <span class="hljs-number">400</span>,
            <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data),
        };
    },
};

<span class="hljs-built_in">module</span>.exports = Responses;
</code></pre>
<p>This set of functions are used to simplify the creation of the correct response needed when using a Lambda with API Gateway (which we'll do in a sec). The methods add headers, a status code, and stringify any data that needs to be returned.</p>
<p>Now that we have the code for our API, we need to set it up in our <code>serverless.yml</code> file. Scroll to the <code>functions</code> section of the <code>serverless.yml</code> file. In the last part of this guide we deployed the <code>hello</code> function, but we no longer need that. Delete the functions object and replace it with this:</p>
<pre><code class="lang-yml"><span class="hljs-attr">functions:</span>
    <span class="hljs-attr">getUser:</span>
        <span class="hljs-attr">handler:</span> <span class="hljs-string">lambdas/endpoints/getUser.handler</span>
        <span class="hljs-attr">events:</span>
            <span class="hljs-bullet">-</span> <span class="hljs-attr">http:</span>
                  <span class="hljs-attr">path:</span> <span class="hljs-string">get-user/{ID}</span>
                  <span class="hljs-attr">method:</span> <span class="hljs-string">GET</span>
                  <span class="hljs-attr">cors:</span> <span class="hljs-literal">true</span>
</code></pre>
<p>This code is creating a new Lambda function called <code>getUser</code> which is in the file of <code>lambdas/getUser</code> on the method of <code>handler</code>. We then define the events that can trigger this lambda function to run.</p>
<p>To make a Lambda into an API we can add a <code>http</code> event. This tells Serverless to add an API Gateway to this account and then we can define the API endpoint using <code>path</code>. In this case <code>get-user/{ID}</code> means the URL will be <code>https://${something-provided-by-API-Gateway}/get-user/{ID}</code>, where the ID is passed into the Lambda as a path parameter. We also set the method to <code>GET</code> and enable CORS so that we could access this endpoint from a front end application if we wanted.</p>
<p>We can now deploy again, and this time we can use the shorthand command <code>sls deploy</code>. This only saves a few characters, but helps avoid a lot of typos. When this is completed we'll get an output that also includes a list of endpoints. We can copy our endpoint and head over to a browser to test it out.</p>
<p><img src="https://completecoding.io/content/images/2019/12/Screenshot-2019-12-10-at-07.19.00.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If we paste our API URL into our browser and then add an ID to the end of 5132 we should get back a response of <code>{ name: 'Tom Hague', age: 23, job: 'plasterer' }</code>. If we enter a different ID such as 1234 we'll get different data, but entering an ID of 7890 or not entering an ID will return an error.</p>
<p>If we want to add more data to our API, we can simply add a new row to the data object in the <code>getUser.js</code> file. We can then run a special command which only deploys one function, <code>sls deploy -f ${functionName}</code>. So for us that is:</p>
<pre><code>sls deploy -f getUser
</code></pre><p>If you now make a request using the ID of the new data, the API will return that new data instead of an error.</p>
<p><a class="anchor" id="dynamo"></a></p>
<h1 id="heading-creating-a-database-on-aws"><strong>Creating a Database on AWS</strong></h1>
<p>DynamoDB is a fully hosted, non-relational database on AWS. This is the perfect solution for storing data that you need to access and update regularly. In this section we're going to learn how we can create a DynamoDB table with Serverless.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/1de8NkTseqM?feature=oembed">Embedded content</a></p>
<p>In our <code>serverless.yml</code> file we're going to add some configuration to the <code>Resources</code> section:</p>
<pre><code>resources:
    Resources:
        DemoBucketUpload:
            Type: AWS::S3::Bucket
            <span class="hljs-attr">Properties</span>:
                BucketName: ${<span class="hljs-attr">self</span>:custom.bucketName}
        # New Code
        <span class="hljs-attr">MyDynamoDbTable</span>:
            Type: AWS::DynamoDB::Table
            <span class="hljs-attr">Properties</span>:
                TableName: ${<span class="hljs-attr">self</span>:custom.tableName}
                <span class="hljs-attr">AttributeDefinitions</span>:
                    - AttributeName: ID
                      <span class="hljs-attr">AttributeType</span>: S
                <span class="hljs-attr">KeySchema</span>:
                    - AttributeName: ID
                      <span class="hljs-attr">KeyType</span>: HASH
                <span class="hljs-attr">BillingMode</span>: PAY_PER_REQUEST
</code></pre><p>In this code we can see that we are creating a new DynamoDB table with a <code>TableName</code> of <code>${self:custom.tableName}</code>, defining an attribute of <code>ID</code> and setting the billing mode to pay per request.</p>
<p>This is our first look at the use of variables in our <code>serverless.yml</code> file. We can use variables for a few reasons and they can make our jobs much easier. In this case, we're referencing the variable <code>custom.tableName</code>. We can then reference this variable from multiple locations without having to copy and paste the table name. To get this to work we also need to add <code>tableName</code> to the custom section. In our case we're going to add the line <code>tableName: player-points</code> to create a table to store the points a player has. This table name only needs to be unique to your account.</p>
<p>When defining a table you need to define at least one of the fields which will be your unique identifying field. Because DynamoDB is a non-relational database, you don't need to define the full schema. In our case we've defined the <code>ID</code>, stating that it has an attribute type of string and a key type of <code>HASH</code>.</p>
<p>The last part of the definition is the billing mode. There are two ways to pay for DynamoDB:</p>
<ul>
<li>pay per request</li>
<li>provisioned resources.</li>
</ul>
<p>Provisioned resources lets you define how much data you're going to be reading and writing to the table. The issues with this are that if you start using more your requests get throttled, and that you pay for the resource even if no one is using it.</p>
<p>Pay Per Request it's much simpler as you just pay per request. This means if you have no one using it then you pay nothing and if your have hundreds of people using it at once, all the requests work. For this added flexibility you pay slightly more for Pay Per Request, but in the long run it usually works out to be cheaper.</p>
<p>Once we've run <code>sls deploy</code> again we can open up our AWS console and search for DynamoDB. We should be able to see our new table and we can see that there is nothing in there.</p>
<p>To add data to the table, click <code>Create item</code>, give it a unique ID, click the plus button and <code>append</code> to a new field and select the type of string. We need to give it a field of <code>name</code> and a value of <code>Jess</code>. Add a number field of <code>score</code> set to <code>12</code>. Click save and you now have data in your dynamo table.</p>
<p><img src="https://completecoding.io/content/images/2019/12/Screenshot-2019-12-10-at-07.57.54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a class="anchor" id="dynamoGet"></a></p>
<h1 id="heading-getting-data-from-your-dynamodb-table"><strong>Getting Data from your DynamoDB Table</strong></h1>
<p>Now that we have our Dynamo table created, we want to be able to get and add data to the table. We're going to start with getting data from the table with a get endpoint.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/CpDFfSXRG04?feature=oembed">Embedded content</a></p>
<p>We're going to create a new file in our <code>endpoints</code> folder called <code>getPlayerScore.js</code>. This Lambda endpoint is going to handle the requests for a user and get that data from the Dynamo table.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Responses = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/API_Responses'</span>);
<span class="hljs-keyword">const</span> Dynamo = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/Dynamo'</span>);

<span class="hljs-keyword">const</span> tableName = process.env.tableName;

<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> event =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event'</span>, event);

    <span class="hljs-keyword">if</span> (!event.pathParameters || !event.pathParameters.ID) {
        <span class="hljs-comment">// failed without an ID</span>
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'missing the ID from the path'</span> });
    }

    <span class="hljs-keyword">let</span> ID = event.pathParameters.ID;

    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> Dynamo.get(ID, tableName).catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error in Dynamo Get'</span>, err);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    });

    <span class="hljs-keyword">if</span> (!user) {
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Failed to get user by ID'</span> });
    }

    <span class="hljs-keyword">return</span> Responses._200({ user });
};
</code></pre>
<p>The code used here is very similar to the code inside the <code>getUser.js</code> file. We are checking that a path parameter of ID exists, getting the user data, and then returning the user. The main difference is how we are getting the user.</p>
<p>We have imported the <code>Dynamo</code> function object and are calling <code>Dynamo.get</code>. We're passing in the ID and the table name and then catching any errors. We now need to create that <code>Dynamo</code> function object in a new file called <code>Dynamo.js</code> in the common folder.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AWS = <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);

<span class="hljs-keyword">const</span> documentClient = <span class="hljs-keyword">new</span> AWS.DynamoDB.DocumentClient();

<span class="hljs-keyword">const</span> Dynamo = {
    <span class="hljs-keyword">async</span> get(ID, TableName) {
        <span class="hljs-keyword">const</span> params = {
            TableName,
            <span class="hljs-attr">Key</span>: {
                ID,
            },
        };

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> documentClient.get(params).promise();

        <span class="hljs-keyword">if</span> (!data || !data.Item) {
            <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`There was an error fetching the data for ID of <span class="hljs-subst">${ID}</span> from <span class="hljs-subst">${TableName}</span>`</span>);
        }
        <span class="hljs-built_in">console</span>.log(data);

        <span class="hljs-keyword">return</span> data.Item;
    },
};
<span class="hljs-built_in">module</span>.exports = Dynamo;
</code></pre>
<p>Reading and writing to Dynamo requires a reasonable amount of code. We could write that code every time we want to use Dynamo but it is much cleaner to have functions to simplify the process for us.</p>
<p>The file first imports AWS and then creates an instance of the DynamoDB Document Client. The document client is the easiest way for us to work with Dynamo from our Lambdas. We create a <code>Dynamo</code> object with an async get function. The only things we need to make a request are an ID and a table name. We format those into the correct parameter format for the DocumentClient, await a <code>documentClient.get</code> request, and make sure that we add <code>.promise()</code> to the end. This turns the request from a callback to a promise which is much easier to work with. We check that we managed to get an item from Dynamo and then we return that item.</p>
<p>We now have the all the code that we need, we have to update our <code>serverless.yml</code> file too. The first thing to do is to add our new API endpoint by adding it to our list of functions.</p>
<pre><code>    getPlayerScore:
        handler: lambdas/endpoints/getPlayerScore.handler
        <span class="hljs-attr">events</span>:
            - http:
                  path: get-player-score/{ID}
                  <span class="hljs-attr">method</span>: GET
                  <span class="hljs-attr">cors</span>: <span class="hljs-literal">true</span>
</code></pre><p>There are two more changes that we need to make to get our endpoint working:</p>
<ul>
<li>environment variables</li>
<li>permissions</li>
</ul>
<p>You may have noticed in the <code>getPlayerScore.js</code> file we had a line of code like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> tableName = process.env.tableName;
</code></pre>
<p>This is where we are getting the table name from the environment variables of the Lambda. To create our Lambda with the correct environment variables, we need to set a new object in the provider called <code>environment</code> with a field of <code>tableName</code> and a value of <code>${self:custom.tableName}</code>. This will ensure that we are making the request to correct table.</p>
<p>We also need to give our Lambdas permissions to access Dynamo. We have to add another field to the provider called <code>iamRoleStatements</code>. This has an array of policies which can allow or disallow access to certain services or resources:</p>
<pre><code>provider:
    name: aws
    <span class="hljs-attr">runtime</span>: nodejs10.x
    <span class="hljs-attr">profile</span>: serverlessUser
    <span class="hljs-attr">region</span>: eu-west<span class="hljs-number">-1</span>
    <span class="hljs-attr">environment</span>:
        tableName: ${<span class="hljs-attr">self</span>:custom.tableName}
    <span class="hljs-attr">iamRoleStatements</span>:
        - Effect: Allow
          <span class="hljs-attr">Action</span>:
              - dynamodb:*
          Resource: <span class="hljs-string">'*'</span>
</code></pre><p>As all this has been added to the provider object, it will be applied to all Lambdas.</p>
<p>We can now run <code>sls deploy</code> again to deploy our new endpoint. When that is done we should get an output with a new endpoint of <code>https://${something-provided-by-API-Gateway}/get-player-score/{ID}</code>. If we copy that URL into a browser tab and add the ID of the player that we created in the last section, we should get a response.</p>
<p><img src="https://completecoding.io/content/images/2019/12/Screenshot-2019-12-10-at-07.59.02.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a class="anchor" id="dynamoPut"></a></p>
<h1 id="heading-adding-new-data-to-dynamodb"><strong>Adding New Data to DynamoDB</strong></h1>
<p>Being able to get data from Dynamo is cool, but it's quite useless if we can't also add new data to the table as well. We're going to be creating a POST endpoint to create new data in our Dynamo table.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/AguTaMQGACE?feature=oembed">Embedded content</a></p>
<p>Start by creating a new file in our endpoints folder called <code>createPlayerScore.js</code> and adding this code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Responses = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/API_Responses'</span>);
<span class="hljs-keyword">const</span> Dynamo = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/Dynamo'</span>);

<span class="hljs-keyword">const</span> tableName = process.env.tableName;

<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> event =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event'</span>, event);

    <span class="hljs-keyword">if</span> (!event.pathParameters || !event.pathParameters.ID) {
        <span class="hljs-comment">// failed without an ID</span>
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'missing the ID from the path'</span> });
    }

    <span class="hljs-keyword">let</span> ID = event.pathParameters.ID;
    <span class="hljs-keyword">const</span> user = <span class="hljs-built_in">JSON</span>.parse(event.body);
    user.ID = ID;

    <span class="hljs-keyword">const</span> newUser = <span class="hljs-keyword">await</span> Dynamo.write(user, tableName).catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error in dynamo write'</span>, err);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    });

    <span class="hljs-keyword">if</span> (!newUser) {
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Failed to write user by ID'</span> });
    }

    <span class="hljs-keyword">return</span> Responses._200({ newUser });
};
</code></pre>
<p>This code is very similar to the <code>getPlayerScore</code> code with a few changes. We are getting the user from the body of the request, adding the ID to the user, and then passing that to a <code>Dynamo.write</code> function. We need to parse the event body as API Gateway stringifies it before passing it to the Lambda.</p>
<p>We now need to modify the common <code>Dynamo.js</code> file to add the <code>.write</code> method. This performs very similar steps to the <code>.get</code> function and returns the newly created data:</p>
<pre><code class="lang-js">    <span class="hljs-keyword">async</span> write(data, TableName) {
        <span class="hljs-keyword">if</span> (!data.ID) {
            <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'no ID on the data'</span>);
        }

        <span class="hljs-keyword">const</span> params = {
            TableName,
            <span class="hljs-attr">Item</span>: data,
        };

        <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> documentClient.put(params).promise();

        <span class="hljs-keyword">if</span> (!res) {
            <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`There was an error inserting ID of <span class="hljs-subst">${data.ID}</span> in table <span class="hljs-subst">${TableName}</span>`</span>);
        }

        <span class="hljs-keyword">return</span> data;
    }
</code></pre>
<p>We've created the endpoint and common code, so the last thing we need to do is modify the <code>serverless.yml</code> file. As we added the environment variable and permissions in the last section, we just need to add the function and API configuration. This endpoint is different from the previous two because the method is <code>POST</code> instead of <code>GET</code>:</p>
<pre><code>    createPlayerScore:
        handler: lambdas/endpoints/createPlayerScore.handler
        <span class="hljs-attr">events</span>:
            - http:
                  path: create-player-score/{ID}
                  <span class="hljs-attr">method</span>: POST
                  <span class="hljs-attr">cors</span>: <span class="hljs-literal">true</span>
</code></pre><p>Deploying this with <code>sls deploy</code> will now create three endpoints, including our <code>create-player-score</code> endpoint. Testing a <code>POST</code> endpoint is more complex than a <code>GET</code> request, but luckily there are tools to help us out. I use <a target="_blank" href="https://www.getpostman.com/">Postman</a> to test all my endpoints as it makes it quick and easy.</p>
<p>Create a new request and paste in your <code>create-player-score</code> URL. You need to change the request type to <code>POST</code> and set the ID at the end of the URL. Because we're doing a POST request we can send up data within the body of the request. Click <code>body</code> then <code>raw</code> and select <code>JSON</code> as the body type. You can then add the data that you want to put into your table. When you click <code>Send</code>, you should get a successful response:</p>
<p><img src="https://completecoding.io/content/images/2019/12/postman.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To validate that your data has been added to the table, you can make a get-player-score request with the ID of the new data you just created. You can also go into the Dynamo console and look at all the items in the table.</p>
<p><a class="anchor" id="s3API"></a></p>
<h1 id="heading-creating-s3-get-and-post-endpoints"><strong>Creating S3 GET and POST Endpoints</strong></h1>
<p>Dynamo is a brilliant database storage solution, but sometimes it isn't the best storage solution. If you've got data that isn't going to change and you want to save some money, or if you want to store files other than JSON, then you might want to consider Amazon S3.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/MlKpK0WqTSs?feature=oembed">Embedded content</a></p>
<p>Creating endpoints to get and create files in S3 is very similar to DynamoDB. We need to create two endpoint files, a common S3 file, and modify the <code>serverless.yml</code> file.</p>
<p>We're going to start with adding a file to S3. Create a <code>createFile.js</code> file in the endpoints folder and add this code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Responses = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/API_Responses'</span>);
<span class="hljs-keyword">const</span> S3 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/S3'</span>);

<span class="hljs-keyword">const</span> bucket = process.env.bucketName;

<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> event =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event'</span>, event);

    <span class="hljs-keyword">if</span> (!event.pathParameters || !event.pathParameters.fileName) {
        <span class="hljs-comment">// failed without an fileName</span>
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'missing the fileName from the path'</span> });
    }

    <span class="hljs-keyword">let</span> fileName = event.pathParameters.fileName;
    <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(event.body);

    <span class="hljs-keyword">const</span> newData = <span class="hljs-keyword">await</span> S3.write(data, fileName, bucket).catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error in S3 write'</span>, err);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    });

    <span class="hljs-keyword">if</span> (!newData) {
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Failed to write data by filename'</span> });
    }

    <span class="hljs-keyword">return</span> Responses._200({ newData });
};
</code></pre>
<p>This code is almost identical to the <code>createPlayerScore.js</code> code, but uses a <code>filename</code> instead of an <code>ID</code> and <code>S3.write</code> instead of <code>Dynamo.write</code>.</p>
<p>Now we need to create our <code>S3</code> common code to simplify requests made to S3:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AWS = <span class="hljs-built_in">require</span>(<span class="hljs-string">'aws-sdk'</span>);
<span class="hljs-keyword">const</span> s3Client = <span class="hljs-keyword">new</span> AWS.S3();

<span class="hljs-keyword">const</span> S3 = {
    <span class="hljs-keyword">async</span> write(data, fileName, bucket) {
        <span class="hljs-keyword">const</span> params = {
            <span class="hljs-attr">Bucket</span>: bucket,
            <span class="hljs-attr">Body</span>: <span class="hljs-built_in">JSON</span>.stringify(data),
            <span class="hljs-attr">Key</span>: fileName,
        };
        <span class="hljs-keyword">const</span> newData = <span class="hljs-keyword">await</span> s3Client.putObject(params).promise();
        <span class="hljs-keyword">if</span> (!newData) {
            <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'there was an error writing the file'</span>);
        }
        <span class="hljs-keyword">return</span> newData;
    },
};
<span class="hljs-built_in">module</span>.exports = S3;
</code></pre>
<p>Again, the code in this file is very similar to the code in <code>Dynamo.js</code>, with a few differences around the parameters for the request.</p>
<p>The last thing we need to do for writing to S3 is change the <code>severless.yml</code> file. We need to do four things: add environment variables, add permissions, add the function, and add an S3 bucket.</p>
<p>In the provider we can add a new environment variable of <code>bucketName: ${self:custom.s3UploadBucket}</code>.</p>
<p>To add permission to read and write to S3 we can add a new permission to the existing policy. Straight after <code>- dynamodb:*</code> we can add the line <code>- s3:*</code>.</p>
<p>Adding the function is the same as we've been doing with all our other functions. Make sure that the path has a parameter of <code>fileName</code> as that is what you are checking for in your endpoint code:</p>
<pre><code>    createFile:
        handler: lambdas/endpoints/createFile.handler
        <span class="hljs-attr">events</span>:
            - http:
                  path: create-file/{fileName}
                  <span class="hljs-attr">method</span>: POST
                  <span class="hljs-attr">cors</span>: <span class="hljs-literal">true</span>
</code></pre><p>Lastly we need to create a new bucket to upload these files into. In the <code>custom</code> section we need to add a new field <code>s3UploadBucket</code> and set it to a unique bucket name. We also need to configure the resource. After the Dynamo table config, we can add this to create a new bucket for our file uploads:</p>
<pre><code>        s3UploadBucket:
            Type: AWS::S3::Bucket
            <span class="hljs-attr">Properties</span>:
                BucketName: ${<span class="hljs-attr">self</span>:custom.s3UploadBucket}
</code></pre><p>With this set up it is time to deploy again. Running <code>sls deploy</code> again will deploy the new upload bucket as well as the S3 write endpoint. To test the write endpoint, we'll need to head back over to Postman.</p>
<p>Copy in the <code>create-file</code> URL that you get when Serverless has completed the deployment and paste it into Postman and change the request type to <code>POST</code>. Next, what we need to do is to add the filename that we are uploading. In our case we're going to be uploading <code>car.json</code>. The last thing we need to do is add the data to the request. Select <code>Body</code> then <code>raw</code> with a type of <code>JSON</code>. You can add whatever JSON data you would like but here's some example data:</p>
<pre><code>{
    <span class="hljs-string">"model"</span>: <span class="hljs-string">"Ford Focus"</span>,
    <span class="hljs-string">"year"</span>: <span class="hljs-number">2018</span>,
    <span class="hljs-string">"colour"</span>: <span class="hljs-string">"red"</span>
}
</code></pre><p>When you post this data up, you should get a <code>200</code> response with an <code>ETag</code> reference to the file. Going into the console and your new S3 bucket you should be able to see <code>car.json</code>.</p>
<h2 id="heading-getting-data-from-s3"><strong>Getting Data from S3</strong></h2>
<p>Now that we can upload data to S3, we want to be able to get it back too. We start by creating a <code>getFile.js</code> file inside the endpoints folder:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Responses = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/API_Responses'</span>);
<span class="hljs-keyword">const</span> S3 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../common/S3'</span>);

<span class="hljs-keyword">const</span> bucket = process.env.bucketName;

<span class="hljs-built_in">exports</span>.handler = <span class="hljs-keyword">async</span> event =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event'</span>, event);

    <span class="hljs-keyword">if</span> (!event.pathParameters || !event.pathParameters.fileName) {
        <span class="hljs-comment">// failed without an fileName</span>
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'missing the fileName from the path'</span> });
    }

    <span class="hljs-keyword">const</span> fileName = event.pathParameters.fileName;

    <span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> S3.get(fileName, bucket).catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'error in S3 get'</span>, err);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
    });

    <span class="hljs-keyword">if</span> (!file) {
        <span class="hljs-keyword">return</span> Responses._400({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Failed to read data by filename'</span> });
    }

    <span class="hljs-keyword">return</span> Responses._200({ file });
};
</code></pre>
<p>This should look pretty similar to previous <code>GET</code> endpoints we've created before. Differences are the use of the <code>fileName</code> path parameter, <code>S3.get</code>, and returning the file.</p>
<p>Inside the common <code>s3.js</code> file we need to add the <code>get</code> function. The main difference between this and getting from Dynamo is that when we get from S3, the result is not a JSON response, but a <code>Buffer</code>. This means that if we upload a JSON file, it won't come back down in JSON format, so we check if we're getting a JSON file and then transform it back to JSON:</p>
<pre><code class="lang-js">    <span class="hljs-keyword">async</span> get(fileName, bucket) {
        <span class="hljs-keyword">const</span> params = {
            <span class="hljs-attr">Bucket</span>: bucket,
            <span class="hljs-attr">Key</span>: fileName,
        };
        <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">await</span> s3Client.getObject(params).promise();
        <span class="hljs-keyword">if</span> (!data) {
            <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Failed to get file <span class="hljs-subst">${fileName}</span>, from <span class="hljs-subst">${bucket}</span>`</span>);
        }
        <span class="hljs-keyword">if</span> (fileName.slice(fileName.length - <span class="hljs-number">4</span>, fileName.length) == <span class="hljs-string">'json'</span>) {
            data = data.Body.toString();
        }
        <span class="hljs-keyword">return</span> data;
    }
</code></pre>
<p>Back in our <code>serverless.yml</code> file, we can add a new function and endpoint for getting files. We've already configured the permissions and environment variables:</p>
<pre><code>    getFile:
        handler: lambdas/endpoints/getFile.handler
        <span class="hljs-attr">events</span>:
            - http:
                  path: get-file/{fileName}
                  <span class="hljs-attr">method</span>: GET
                  <span class="hljs-attr">cors</span>: <span class="hljs-literal">true</span>
</code></pre><p>As we're creating a new endpoint we need to do a full deployment again with <code>sls deploy</code>. We can then take the new <code>get-file</code> endpoint and paste it into a browser or Postman. If we add <code>car.json</code> to the end of the request we'll receive the JSON data that we uploaded earlier in this section.</p>
<p><a class="anchor" id="l9apikey"></a></p>
<h1 id="heading-securing-your-endpoints-with-api-keys"><strong>Securing Your Endpoints with API Keys</strong></h1>
<p>Being able to create API endpoints quickly and easily with Serverless is great for starting a project and creating a proof of concept. When it comes to creating a production version of your application, you need to start being more careful about who can access your endpoints. You don't want anybody being able to hit your APIs.</p>
<p><a target="_blank" href="https://www.youtube.com/embed/n5aSq1L5nIw?feature=oembed">Embedded content</a></p>
<p>To secure your APIs there are loads of methods, and in this section we're going to be implementing API keys. If you don't pass the API key with the request then it fails with an unauthorised message. You can then control who you give the API keys to, and therefore who has access to your APIs.</p>
<p>You can also add usage policies to your API keys so that you can control how much each person uses your API. This allows you to created tiered usage plans for your service.</p>
<p>To start we're going to be creating a simple API Key. To do this we need to go into our <code>serverless.yml</code> file and add some configuration to the provider.</p>
<pre><code class="lang-js">    apiKeys:
        myFirstAPIKey
</code></pre>
<p>This will create a new API key. Now we need to tell Serverless which API endpoints to protect with the API key. This has been done so that we can have some of the APIs protected, whilst some of them stay public. We specify that an endpoint needs to be protected by adding the option <code>private: true</code>:</p>
<pre><code class="lang-js">    getUser:
        handler: lambdas/endpoints/getUser.handler
        <span class="hljs-attr">events</span>:
            - http:
                  path: get-user/{ID}
                  <span class="hljs-attr">method</span>: GET
                  <span class="hljs-attr">cors</span>: <span class="hljs-literal">true</span>
                  <span class="hljs-attr">private</span>: <span class="hljs-literal">true</span>
</code></pre>
<p>You can then add this field to as many of your APIs as you would like. To deploy this we can run <code>sls deploy</code> again. When this completes, you will get back an API key in the return values. This is very important and we'll use it very soon. If you try and make a request to your <code>get-user</code> API you should get a 401 Unauthorised error.</p>
<p>To get the request to succeed, you now need to pass up an API key in the headers of the request. To do this we need to use Postman or another API request tool and add header to our get request. We do this by selecting <code>Authorisation</code> using the <code>API type</code>. The key needs to be <code>X-API-KEY</code> and the value is the key that you got as an output from your Serverless deploy:</p>
<p><img src="https://completecoding.io/content/images/2019/12/Screenshot-2019-12-20-at-20.05.53.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now when we make the request we get a successful response. This means that the only people who can access your API are people who you have given your API key to.</p>
<p>This is great, but we can do more. We can add a usage policy to this API key. This is where we can limit the number of requests a month as well as the rate at which requests can be made. This is great for running a SAAS product as you can provide an API key that gives users a set amount of API calls.</p>
<p>To create a usage plan we need to add a new object in the provider. The <code>quota</code> section defines how many requests can be made using that API key. You can change the period to either <code>DAY</code> or <code>WEEK</code> if that would suit your application better.</p>
<p>The <code>throttle</code> section allows you to control how frequently your API endpoints can be hit. Adding a throttle <code>rate limit</code> sets a maximum number of requests per second. This is very useful as it stops people from setting up a denial of service attack. The <code>burstLimit</code> allows the API to be hit more often than your <code>rateLimit</code> but only for a short period of time, normally a few seconds:</p>
<pre><code>    usagePlan:
        quota:
            limit: <span class="hljs-number">10</span>
            <span class="hljs-attr">period</span>: MONTH
        <span class="hljs-attr">throttle</span>:
            burstLimit: <span class="hljs-number">2</span>
            <span class="hljs-attr">rateLimit</span>: <span class="hljs-number">1</span>
</code></pre><p>If we were to deploy this again, the deployment would fail as we would be trying to deploy the same API key. API keys need to be unique so we have to change the name of the API key. When we deploy this and copy our new API key into Postman, we'll be able to make requests as we normally would. If we try and make too many requests per second or reach the maximum number of requests then we'll get a 429 error of</p>
<pre><code>{
    <span class="hljs-string">"message"</span>: <span class="hljs-string">"Limit Exceeded"</span>
}
</code></pre><p>This means that you can't use this API key again until next month.</p>
<p>Whilst creating a usage plan is great, you often want to give different people different levels of access to your services. You might give free users 100 requests per month and paying users get 1000. You might want different payment plans which give different number of requests. You would also probably want a master API key for yourself which has unlimited requests!</p>
<p>To do this we can set up multiple groups of API keys that each have their own usage policy. We need to change the <code>apiKeys</code> and <code>usagePlan</code> sections:</p>
<pre><code>    apiKeys:
        - free:
              - MyAPIKey3
        - paid:
              - MyPaidKey3
    <span class="hljs-attr">usagePlan</span>:
        - free:
              quota:
                  limit: <span class="hljs-number">10</span>
                  <span class="hljs-attr">period</span>: MONTH
              <span class="hljs-attr">throttle</span>:
                  burstLimit: <span class="hljs-number">2</span>
                  <span class="hljs-attr">rateLimit</span>: <span class="hljs-number">1</span>
        - paid:
              quota:
                  period: MONTH
                  <span class="hljs-attr">limit</span>: <span class="hljs-number">1000</span>
              <span class="hljs-attr">throttle</span>:
                  burstLimit: <span class="hljs-number">20</span>
                  <span class="hljs-attr">rateLimit</span>: <span class="hljs-number">10</span>
</code></pre><p>Once you've saved and deployed this you'll get two new API keys, each with a different level of access to your API endpoints.</p>


<p>Thanks for reading this guide! If you've found it useful, please subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UC8uBP0Un18DJAnWjm1CPqBg">Youtube channel</a> where I release weekly videos on Serverless and software development.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Multithreading in Java: How to Get Started with Threads ]]>
                </title>
                <description>
                    <![CDATA[ By Aditya Sridhar What is a Thread? A thread is a lightweight process. Any process can have multiple threads running in it. For example in a web browser, we can have one thread which will load the user interface and another thread which will actually... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-started-with-multithreading-in-java/</link>
                <guid isPermaLink="false">66d45d65b3016bf139028d19</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Threading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 13 Dec 2019 13:45:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/how-to-get-started-with-multithreading-in-java.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aditya Sridhar</p>
<h1 id="heading-what-is-a-thread">What is a Thread?</h1>
<p>A thread is a lightweight process. Any process can have multiple threads running in it.</p>
<p>For example in a web browser, we can have one thread which will load the user interface and another thread which will actually retrieve all the data that needs to be displayed in that interface.</p>
<h1 id="heading-what-is-multithreading">What is MultiThreading?</h1>
<p>Multithreading enables us to run multiple threads concurrently.</p>
<p>For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed.</p>
<p>So multithreading improves the responsiveness of a system.</p>
<h1 id="heading-what-is-concurrency">What is Concurrency?</h1>
<p>Concurrency in the context of threads enables us to run multiple threads at the same time.</p>
<p>But do the threads really run at the same time?</p>
<h2 id="heading-single-core-systems">Single Core Systems</h2>
<p>The <strong>Thread Scheduler</strong> provided by the JVM decides which thread runs at any given time. The scheduler gives a small time slice to each thread.</p>
<p>So at any given time we have only one thread which is actually running in the processor. But because of the time slicing we get the feeling that multiple threads are running at the same time.</p>
<h2 id="heading-multi-core-systems">Multi Core Systems</h2>
<p>Even in multiple core systems the thread scheduler is involved. But since we have multiple cores, we can actually have multiple threads running at the exact same time.</p>
<p>For example if we have a dual core system, then we can have 2 threads running at the exact same time. The first thread will run in the first core, and the second thread will run in the second core.</p>
<h1 id="heading-why-is-multithreading-needed">Why is Multithreading needed?</h1>
<p>Multithreading enables us to improve the responsiveness of a system.</p>
<p>For example in a web browser, if everything ran in a single thread, then system would be completely unresponsive whenever data was being fetched to display. For example, if it takes 10 seconds to fetch the data, then in that 10 seconds we wont be able to do anything else in the web browser like opening new tabs, or even closing the web browser.</p>
<p>So running different parts of a program in different threads concurrently helps improve the responsiveness of a system.</p>
<h1 id="heading-how-to-write-multithreaded-programs-in-java">How to write Multithreaded Programs in Java</h1>
<p>We can create threads in Java using the following</p>
<ul>
<li>Extending the thread class</li>
<li>Implementing the runnable interface</li>
<li>Implementing the callable interface</li>
<li>By using the executor framework along with runnable and callable tasks</li>
</ul>
<p>We will look at callables and the executor framework in a separate blog. In this article I will be mainly focussing on extending the thread class and implementing the runnable interface.</p>
<h2 id="heading-extending-the-thread-class">Extending the Thread Class</h2>
<p>In order to create a piece of code which can be run in a thread, we create a class and then extend the <strong>thread</strong> class. The task being done by this piece of code needs to be put in the <strong>run()</strong> function. </p>
<p>In the below code you can see that <strong>worker</strong> is a class which extends the <strong>thread</strong> class, and the task of printing numbers 0 to 5 is being done inside the <strong>run()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}
</code></pre>
<p>In the above code <strong>Thread.currentThread().getName()</strong> is used to get the name of the current thread which is running the code.</p>
<p>In order to create a <strong>thread</strong>, we just need to create an instance of the worker class. And then we can start the thread using the <strong>start()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadClassDemo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Thread t1 = <span class="hljs-keyword">new</span> Worker();
        Thread t2 = <span class="hljs-keyword">new</span> Worker();
        Thread t3 = <span class="hljs-keyword">new</span> Worker();
        t1.start();
        t2.start();
        t3.start();

    }
}
</code></pre>
<p>In the above code, we are creating 3 threads (t1,t2 and t3) from the worker class. Then we are starting the threads using the <strong>start()</strong> function.</p>
<p>Here is the final code for creating a thread by extending a thread class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadClassDemo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Thread t1 = <span class="hljs-keyword">new</span> Worker();
        Thread t2 = <span class="hljs-keyword">new</span> Worker();
        Thread t3 = <span class="hljs-keyword">new</span> Worker();
        t1.start();
        t2.start();
        t3.start();

    }
}
</code></pre>
<p>Here is the output we get by running the above code:</p>
<p><img src="https://adityasridhar.com/assets/img/posts/how-to-get-started-with-multithreading-in-java/thread-class-output.png" alt="Thread Class output" width="525" height="295" loading="lazy"></p>
<p>You can see that all the 3 threads have printed the numbers from 0 to 5.</p>
<p><strong>You can also clearly see from the output that the 3 threads do not run in any particular sequence</strong></p>
<h2 id="heading-implementing-the-runnable-interface">Implementing the Runnable Interface</h2>
<p>In order to create a piece of code which can be run in a thread, we create a class and then implement the <strong>runnable</strong> interface. The task being done by this piece of code needs to be put in the <strong>run()</strong> function. </p>
<p>In the below code you can see that <strong>RunnableWorker</strong> is a class which implements <strong>runnable</strong> interface, and the task of printing numbers 0 to 4 is being done inside the <strong>run()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableWorker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}
</code></pre>
<p>In order to create a thread, first we need to create an Instance of <strong>RunnableWorker</strong> which implements the <strong>runnable</strong> interface.</p>
<p>Then we can create a new thread by creating an instance of the <strong>thread</strong> class and passing the instance of <strong>RunnableWorker</strong> as the argument. This is shown in the code below:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Runnable r = <span class="hljs-keyword">new</span> RunnableWorker();
        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();

    }

}
</code></pre>
<p>The above code creates a runnable instance r. Then it create 3 threads (t1, t2 and t3) and passes <strong>r</strong> as the argument to the 3 threads. Then the <strong>start()</strong> function is used to start all 3 threads.</p>
<p>Here is the complete code for creating a thread by implementing the runnable interface:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableWorker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Runnable r = <span class="hljs-keyword">new</span> RunnableWorker();
        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();

    }

}
</code></pre>
<p>On running the above code, we will get the following output. The sequence of the output will change every time the code is run.</p>
<p><img src="https://adityasridhar.com/assets/img/posts/how-to-get-started-with-multithreading-in-java/runnable-interface-output.png" alt="Runnable Interface output" width="431" height="242" loading="lazy"></p>
<p><strong>Implementing the runnable interface is a better option than extending the thread class since we can extend only one class, but we can implement multiple interfaces in Java.</strong></p>
<h2 id="heading-runnable-interface-in-java-8">Runnable Interface in Java 8</h2>
<p>In Java 8, the runnable interface becomes a <strong>FunctionalInterface</strong> since it has only one function, <strong>run()</strong>.</p>
<p>The below code shows how we can create a runnable instance in Java 8.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableFunctionalInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        Runnable r = () -&gt; {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
                System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
            }
        };

        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();
    }

}
</code></pre>
<p>Here, instead of creating a class and then implementing the runnable interface, we can directly use a lambda expression to create a runnable instance as shown below:</p>
<pre><code class="lang-java">Runnable r = () -&gt; {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    };
</code></pre>
<h1 id="heading-code">Code</h1>
<p>The code in this article is available in the following GitHub repo: <a target="_blank" href="https://github.com/aditya-sridhar/basic-threads-demo">https://github.com/aditya-sridhar/basic-threads-demo</a></p>
<h1 id="heading-congrats">Congrats ?</h1>
<p>You now know how to create threads by extending the thread class and by implementing the runnable interface.</p>
<p>I will discuss the thread life cycle and challenges while using threads in my next blog post.</p>
<p><strong>My Website</strong>: <a target="_blank" href="https://adityasridhar.com/">https://adityasridhar.com/</a></p>
<h3 id="heading-feel-free-to-connect-with-me-on-linkedinhttpswwwlinkedincominaditya1811-or-follow-me-on-twitterhttpswwwtwittercomadityasridhar18">Feel free to connect with me on <a target="_blank" href="https://www.linkedin.com/in/aditya1811">LinkedIn</a> or follow me on <a target="_blank" href="https://www.twitter.com/adityasridhar18">Twitter</a></h3>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
