<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anil Kumar Valluru on Medium]]></title>
        <description><![CDATA[Stories by Anil Kumar Valluru on Medium]]></description>
        <link>https://medium.com/@anilkumarvalluru?source=rss-5b2e96c6de9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kkHisf16XMPbFWbmbPQOpw.png</url>
            <title>Stories by Anil Kumar Valluru on Medium</title>
            <link>https://medium.com/@anilkumarvalluru?source=rss-5b2e96c6de9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:21:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anilkumarvalluru/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Connected Claude AI to TradingView — Now It Reads My Charts, Write Pine Scripts & Scan Markets]]></title>
            <link>https://anilkumarvalluru.medium.com/i-connected-claude-ai-to-tradingview-now-it-reads-my-charts-write-pine-scripts-scan-markets-612ba5431cdc?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/612ba5431cdc</guid>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Sun, 03 May 2026 05:07:34 GMT</pubDate>
            <atom:updated>2026-05-03T05:07:34.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUPscTqXE6oYCWIfgLLhMA.png" /></figure><p>Imagine this.</p><p>You open your TradingView. Instead of staring at candles and guessing what’s going on, you just type:</p><blockquote>“Analyze this chart and give me intraday bias”<br>“Write a Pine Script for EMA crossover”<br> “Scan Nifty50 for momentum stocks”</blockquote><p>And claude will look at your chart and give you a response based on what’s actually happening there.</p><p>No magic. Just a smart setup.</p><p>Let me walk you through the <strong>complete setup </strong>and how the system actually works.</p><h3>🧠 What’s Really Happening Here?</h3><p>Think of this like giving your charts a voice assistant.</p><p>You know how you ask your phone:</p><blockquote>“What’s the weather?”</blockquote><p>Now imagine asking your chart:</p><blockquote>“Where is support?”<br> “What’s the momentum?”</blockquote><p>At a high level, this system connects an LLM to your live chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*JE0zI-5iXe19q5p-ZURk7Q.png" /></figure><p><strong>What this enables:</strong></p><ul><li>Claude can <strong>read your chart</strong></li><li>Modify indicators and symbols</li><li>Generate Pine Scripts</li><li>Automate chart interactions</li></ul><p>So instead of clicking around, you just talk to it.</p><h4>⚠️ One Important Thing (Don’t Skip This)</h4><p>You can’t use the TradingView desktop app for this.</p><p><strong>Why?</strong></p><ul><li>It’s a Microsoft Store / packaged app</li><li>No access to Chrome DevTools Protocol</li><li>Cannot run with debug flags</li></ul><p>👉 Solution: Use TradingView in Google Chrome with remote debugging enabled.</p><h3>🪟 If You’re on Windows</h3><p>Let’s keep this simple.</p><p><strong>Step 1: Open TradingView in a Special Way</strong></p><p>You’re not opening Chrome normally. You’re opening it in “developer mode.”</p><p>Paste this into Command Prompt:</p><pre>&quot;C:\Program Files\Google\Chrome\Application\chrome.exe&quot; --remote-debugging-port=9222 --user-data-dir=&quot;%TEMP%\chrome-tv&quot; https://tradingview.com/chart/</pre><p>This:</p><ul><li>Opens a fresh Chrome instance</li><li>Enables remote debugging</li><li>Exposes your TradingView tab to external tools</li></ul><p>Log into TradingView like you normally would.</p><p><strong>Step 2: Check If It’s Working</strong></p><p>Run this:</p><pre>curl http://localhost:9222/json</pre><p>If working, you’ll see JSON output like:</p><pre>&quot;title&quot;: &quot;NIFTY 23,997.55 ▼ −0.74%&quot;</pre><p>You’re good.</p><p>That means your chart is “visible” to the system.</p><p><strong>Step 3: Install Node.js</strong></p><p>Download and install the LTS version of <a href="https://nodejs.org/en/download">Node.js</a>.</p><p>Then check:</p><pre>node -v<br>npm -v</pre><p><strong>Step 4: Install Claude CLI</strong></p><pre>npm install -g @anthropic-ai/claude-code<br>claude</pre><p>Log in with your account.</p><p><strong>Step 5: Clone MCP Server</strong></p><pre>git clone https://github.com/tradesdontlie/tradingview-mcp.git<br>cd tradingview-mcp<br>npm install</pre><p>👉 This step is <strong>mandatory</strong>. Without it, the server won’t run.</p><p><strong>Step 6: Connect MCP to Claude</strong></p><pre>claude mcp add tradingview node &quot;C:\Users\YOURUSERNAME\tradingview-mcp\src\server.js&quot;</pre><p>Then:</p><pre>claude<br>/mcp</pre><p>You should see:</p><pre>tradingview ✓ connected</pre><h3>🐧 If You’re on Linux (or WSL)</h3><p><strong>Step 0: Install Google Chrome (Don’t skip this)<br></strong>Most Linux systems don’t come with Chrome pre-installed.</p><pre>wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb<br>sudo apt install ./google-chrome-stable_current_amd64.deb</pre><p>Then check:</p><pre>google-chrome --version</pre><p>If you see a version number, you’re good.</p><p><strong>Step 1: Install Dependencies</strong></p><pre>sudo apt update<br>sudo apt install nodejs npm git curl</pre><p><strong>Step 2: Launch Chrome with Debug Port</strong></p><pre>google-chrome \<br>--remote-debugging-port=9222 \<br>--user-data-dir=/tmp/chrome-tv \<br>https://tradingview.com/chart/</pre><p><strong>Step 3: Test the Connection</strong></p><pre>curl http://localhost:9222/json</pre><p><strong>Step 4: Install Claude CLI</strong></p><pre>npm install -g @anthropic-ai/claude-code<br>claude</pre><p><strong>Step 5: Clone MCP Server</strong></p><pre>git clone https://github.com/tradesdontlie/tradingview-mcp.git<br>cd tradingview-mcp<br>npm install</pre><p><strong>Step 6: Connect MCP</strong></p><pre>claude mcp add tradingview node &quot;/home/YOURUSERNAME/tradingview-mcp/src/server.js&quot;</pre><h3>🍎 If You’re on macOS</h3><p>Again, same flow.</p><p>Install tools</p><pre>brew install node git curl</pre><p>Open Chrome</p><pre>/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \<br>--remote-debugging-port=9222 \<br>--user-data-dir=/tmp/chrome-tv \<br>https://tradingview.com/chart/</pre><h3>Finish setup</h3><p>Same as before:</p><ul><li>Install Claude</li><li>Clone repo</li><li>Run npm install</li><li>Connect MCP</li></ul><h3>🔥 What You Can Do Now (This Is Where It Gets Fun)</h3><p>Once it’s connected, you don’t “use TradingView” the same way anymore.</p><p>You talk to it.</p><p><strong>📊 Ask for analysis</strong></p><blockquote>“Analyze this chart and give today’s bias”<br>“What’s the trend here?”<br> “Is this bullish or bearish today?”</blockquote><p><strong>🔄 Change charts instantly</strong></p><blockquote>“Switch to NSE:BANKNIFTY on 15-minute timeframe”</blockquote><p><strong>✍️ Write pinescripts</strong></p><blockquote>“Write a Pine Script for EMA crossover with alerts”</blockquote><p><strong>📐 Draw levels</strong></p><blockquote>“Draw support at 23,900 and resistance at 24,044”</blockquote><p><strong>🔔 Set alerts</strong></p><blockquote>“Notify me when Nifty breaks previous high”</blockquote><p><strong>🏆 Scan stocks</strong></p><blockquote>“Scan Nifty50 for momentum breakout stocks”</blockquote><h3>🧩 Why This Feels Different</h3><p>Normally, trading looks like this:</p><ul><li>Click indicator</li><li>Adjust settings</li><li>Guess what it means</li></ul><p>Now it’s more like:</p><ul><li>Ask a question</li><li>Get a structured answer</li><li>Move faster</li></ul><p>It’s like going from:</p><blockquote><em>calculator → to → smart assistant</em></blockquote><h4><strong>⚠️ Quick Reality Check</strong></h4><p>Don’t treat this like a magic trading bot.</p><p>Claude can:</p><ul><li>misunderstand charts</li><li>give wrong signals</li><li>miss context</li></ul><p>So use it like a helper, not a decision-maker.</p><h4>🚨 If Something Breaks</h4><p>Most common issue:</p><pre>Failed to reconnect to tradingview</pre><p>Usually means:</p><ul><li>Chrome not opened with debug mode</li><li>Port already used</li><li>You skipped npm install</li></ul><p>Fix:</p><ol><li>Close Chrome</li><li>Restart with the command</li><li>Run npm install again</li><li>Retry /mcp</li></ol><h4>💬 Final Thoughts</h4><p>We’re stepping into a new phase of trading.</p><p>Charts aren’t just dashboards anymore.<br>They’re becoming programmable, AI-driven interfaces.</p><p>If you learn to integrate systems like this, you gain:</p><ul><li>Faster analysis</li><li>Better experimentation</li><li>Reduced manual workload</li></ul><p>If this helped you, drop a clap and share it with a friend who spends too much time staring at charts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=612ba5431cdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your FastAPI Performance with ProtoBuf: The Key to Efficient, High-Speed APIs]]></title>
            <link>https://anilkumarvalluru.medium.com/boost-your-fastapi-performance-with-protobuf-the-key-to-efficient-high-speed-apis-e778edfe2870?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e778edfe2870</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 03:59:47 GMT</pubDate>
            <atom:updated>2024-10-16T03:59:47.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*4UIgT895YUAypAlwXJaJrg.png" /></figure><p>Data serialization is a crucial aspect of modern APIs. When building applications that need to communicate efficiently over the network or store data, using a compact and efficient format is highly advantageous. In this article, we’ll explore how to use Protocol Buffers (<strong>ProtoBuf</strong>) with <strong>FastAPI </strong>and discuss why ProtoBuf is an excellent choice for data serialization.</p><h3>What is Protocol Buffers?</h3><p>Protocol Buffers, or ProtoBuf, is a language-neutral, platform-neutral mechanism for serializing structured data. It was developed by <strong>Google </strong>to efficiently exchange information between services. Unlike <strong>JSON </strong>or <strong>XML</strong>, <strong>ProtoBuf </strong>is a binary serialization format, which makes it significantly faster and more compact. This is particularly important in distributed systems where high performance is essential.</p><h3>Why Use ProtoBuf with FastAPI?</h3><p>FastAPI is a modern, high-performance web framework for building APIs with Python. It supports asynchronous programming, dependency injection, and automatic API documentation, making it an excellent choice for rapid development. When combined with ProtoBuf, FastAPI can become even more powerful for the following reasons:</p><ol><li><strong>Compact and Efficient Data Format</strong>: <br>ProtoBuf is more compact than JSON, resulting in smaller payload sizes, which means lower bandwidth usage and faster transmission.</li><li><strong>Serialization Performance</strong>: <br>Since ProtoBuf uses binary encoding, it significantly improves the performance of serialization and deserialization compared to traditional text-based formats.</li><li><strong>Strong Typing</strong>: <br>ProtoBuf defines the data structure explicitly, ensuring that the data format remains consistent across different components of your system.</li><li><strong>Backward and Forward Compatibility</strong>: <br>ProtoBuf allows developers to modify message definitions while keeping backward compatibility, which is crucial for maintaining large-scale distributed systems.</li></ol><h3>Setting Up ProtoBuf with FastAPI</h3><p>Let’s look at how we can integrate ProtoBuf with FastAPI.</p><h4>Step 1: Install Required Packages</h4><p>To get started, you need to install the necessary packages for working with ProtoBuf and FastAPI. Use the following command to install protobuf, fastapi, and uvicorn (an ASGI server for running FastAPI):</p><pre>pip install protobuf fastapi uvicorn</pre><p>You will also need the protoc compiler, which you can install depending on your operating system:</p><ul><li><strong>Linux</strong>: Use your package manager, e.g., sudo apt-get install protobuf-compiler.</li><li><strong>macOS</strong>: Install via Homebrew, e.g., brew install protobuf.</li><li><strong>Windows</strong>: Download the protoc binary from the official <a href="https://github.com/protocolbuffers/protobuf/releases">Protocol Buffers GitHub releases</a>.</li></ul><h4>Step 2: Define Your Proto File</h4><p>Create a .proto file that defines the structure of your data. Here’s an example called product.proto:</p><pre>syntax = &quot;proto3&quot;;<br><br>message Product {<br>  int32 id = 1;<br>  string name = 2;<br>  string description = 3;<br>  float price = 4;<br>  int32 quantity = 5;<br>  string category = 6;<br>  string manufacturer = 7;<br>  bool is_available = 8;<br>  repeated string tags = 9;<br>}</pre><p>In this file, we define a Product message with fields: id, name, description, price, quantity, category, manufacturer, is_available, and tags.</p><h4>Step 3: Compile the Proto File</h4><p>To use the ProtoBuf message in Python, you need to compile the .proto file using the protoc compiler:</p><pre>protoc --python_out=. product.proto</pre><p>This will generate a Python file (product_pb2.py) that you can import into your FastAPI application.</p><h4>Step 4: Integrate with FastAPI</h4><p>Here’s how you can use the compiled ProtoBuf file in your FastAPI app:</p><pre>from fastapi import FastAPI<br>import product_pb2<br>import sqlite3<br>from fastapi import FastAPI, Response<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/products&quot;)<br>async def list_products():<br>    # Connect to the SQLite database<br>    conn = sqlite3.connect(&quot;products.db&quot;)<br>    try:<br>        cursor = conn.cursor()<br>        # Query the products from the database<br>        cursor.execute(<br>            &quot;SELECT id, name, description, price, stock_quantity, category, manufacturer, is_available FROM products&quot;<br>        )<br>        rows = cursor.fetchall()<br><br>        # Convert database rows to Product messages<br>        products = [<br>            product_pb2.Product(<br>                id=row[0],<br>                name=row[1],<br>                description=row[2],<br>                price=row[3],<br>                quantity=row[4],<br>                category=row[5],<br>                manufacturer=row[6],<br>                is_available=bool(row[7]),<br>                tags=(<br>                    row[8] if len(row) &gt; 8 else []<br>                ),<br>            )<br>            for row in rows<br>        ]<br><br>        # Serialize the products into a list of binary data<br>        serialized_products = [product.SerializeToString() for product in products]<br><br>        # Combine the serialized products into a single response<br>        response_content = b&quot;&quot;.join(serialized_products)<br>        return Response(content=response_content, media_type=&quot;application/octet-stream&quot;)<br>    finally:<br>        cursor.close()<br>        conn.close()</pre><p>In this example:</p><ul><li>We import the generated product_pb2 module.</li><li>The /products endpoint retrieves product data from the SQLite database, converts it into Product messages, and serializes them.</li><li>Finally, we return the serialized response back to the client using a streaming response.</li></ul><h3>LinkedIn Integrates ProtoBuf with REST.li</h3><p>LinkedIn has successfully integrated Protocol Buffers with REST.li to improve the efficiency and performance of their data serialization. By using ProtoBuf, LinkedIn achieved up to a <strong>60% </strong>reduction in latency and an 8% improvement in resource utilization across their services. ProtoBuf replaced JSON as the serialization format, significantly reducing payload sizes and improving throughput.</p><p>LinkedIn also saw improvements in average throughput per host, with a <strong>6.25%</strong> increase for response payloads and a <strong>1.77%</strong> increase for request payloads. This use case demonstrates ProtoBuf’s effectiveness in a large-scale infrastructure where reducing latency and improving throughput is crucial. More details on this can be found in their official <a href="https://www.linkedin.com/blog/engineering/infrastructure/linkedin-integrates-protocol-buffers-with-rest-li-for-improved-m">LinkedIn Engineering Blog</a>.</p><h3>Advantages of Using ProtoBuf with FastAPI</h3><ol><li><strong>Improved Performance</strong>: <br>The binary format used by ProtoBuf is much faster to parse than JSON, reducing CPU usage and improving response times.</li><li><strong>Reduced Bandwidth</strong>: <br>ProtoBuf’s compact size results in smaller payloads, which is particularly beneficial for mobile applications or services with limited bandwidth.</li><li><strong>Type Safety</strong>: <br>ProtoBuf enforces strict typing, reducing errors related to incorrect data types and ensuring that the API contract is adhered to.</li><li><strong>Compatibility and Evolution</strong>: <br>ProtoBuf supports backward and forward compatibility. Fields can be added or deprecated without breaking existing clients, making it ideal for evolving APIs.</li></ol><h3>When to Use ProtoBuf Over JSON</h3><p>ProtoBuf is ideal for scenarios where performance is critical, such as:</p><ul><li><strong>Microservices communication</strong>:<br>When different services exchange data frequently, ProtoBuf’s efficiency makes a noticeable difference.</li><li><strong>Mobile applications</strong>:<br>ProtoBuf’s compact payloads help reduce data usage for mobile clients.</li><li><strong>High-throughput APIs</strong>:<br>For APIs with large data volumes or high request rates, ProtoBuf’s speed and efficiency offer a significant performance boost.</li></ul><p>However, for simple APIs where human readability and ease of use are more important, JSON might still be preferable due to its simplicity and ease of debugging.</p><p>Integrating ProtoBuf with <strong>FastAPI </strong>can significantly improve your API’s performance, particularly when dealing with high-throughput or bandwidth-sensitive applications. While ProtoBuf may have a steeper learning curve compared to <strong>JSON</strong>, its benefits in terms of speed, efficiency, and type safety make it a powerful tool for optimizing data serialization.</p><p>If you’re building microservices or mobile-friendly APIs and need efficiency, consider giving <strong>ProtoBuf </strong>a try with your FastAPI project.</p><p>Frontend frameworks can also interact with ProtoBuf APIs by either using JavaScript libraries like protobufjs or relying on the backend to convert ProtoBuf messages into JSON. If you’re building microservices or mobile-friendly APIs and need efficiency, consider giving ProtoBuf a try with your FastAPI project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e778edfe2870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs Web vs SOAP: When to use them?]]></title>
            <link>https://anilkumarvalluru.medium.com/rest-vs-web-vs-soap-when-to-use-them-279bd3bf7956?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/279bd3bf7956</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 05:28:28 GMT</pubDate>
            <atom:updated>2024-10-13T05:28:28.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*dJB0FGe3Xc9cYiAFuTdpDA.png" /><figcaption>REST vs Web vs SOAP</figcaption></figure><p><strong>Application Programming Interfaces (APIs)</strong> are essential for modern software systems, enabling seamless interaction between different software components. However, the wide variety of API types can make it challenging to understand their differences and appropriate use cases. In this article I will share an in-depth comparison of three widely used API models: <strong>REST API</strong>, <strong>Web API</strong>, and <strong>SOAP</strong>.</p><h3><strong>What is an API?</strong></h3><p>An <strong>API (Application Programming Interface)</strong> acts as an intermediary that allows systems to communicate with each other. APIs serve as a bridge that enables one application to access the data or functionality of another without needing to understand its internal workings. You can think of an API as a waiter in a restaurant: it takes your order (client request), communicates it to the kitchen (server), and brings back your food (response).</p><h3>REST API</h3><p><strong>REST (Representational State Transfer)</strong> is an architectural style for developing web services and systems that can easily communicate with each other. RESTful APIs are stateless, meaning that every request from a client must include all the information needed for the server to process it. Here are some key features of REST:</p><ul><li><strong>Stateless Communication</strong>: REST does not require the server to remember previous client requests, which makes the system scalable. The stateless client-server model ensures that each request is self-contained, making REST highly scalable and easier to maintain.</li><li><strong>Resource-Based</strong>: REST focuses on resources, and each resource is identified by a unique URL. Resources can be entities such as users, posts, or products.</li><li><strong>HTTP Methods</strong>: REST APIs make use of standard HTTP methods to perform operations on resources:</li><li><strong>GET</strong>: Retrieve data.</li><li><strong>POST</strong>: Create new data.</li><li><strong>PUT</strong> or <strong>PATCH</strong>: Update existing data.</li><li><strong>DELETE</strong>: Remove data.</li><li><strong>Data Formats</strong>: REST APIs typically use <strong>JSON</strong> or <strong>XML</strong> for data exchange, offering flexibility depending on the application requirements.</li><li><strong>Use Cases</strong>: REST APIs are commonly used for building scalable web services, including web, mobile, and desktop applications, due to their simplicity and compatibility with web technologies.</li></ul><p>REST APIs are popular due to their simplicity, scalability, and compatibility with web technologies, making them suitable for distributed systems.</p><h3>Web API</h3><p><strong>Web API</strong> is a broad term that refers to any API that can be accessed over the web using the HTTP protocol. In that sense, <strong>REST APIs are a subset of Web APIs</strong>. Web APIs can be implemented using various protocols, including REST, SOAP, or even GraphQL.</p><p>The term “Web API” does not imply a specific design style and can refer to:</p><ul><li>A <strong>RESTful API</strong> that uses HTTP.</li><li>An API based on <strong>GraphQL</strong> for querying and manipulating data.</li><li>A <strong>SOAP API</strong>, which will be discussed next.</li></ul><p>In short, all REST APIs are Web APIs, but not all Web APIs are RESTful. The term “Web API” covers any web-based service regardless of its underlying protocol.</p><p>Key characteristics of Web APIs include:</p><ul><li><strong>Platform-Independent Interface</strong>: Web APIs provide a platform-independent way for different devices, such as desktops, tablets, and smartphones, to communicate with each other.</li><li><strong>Supports Multiple Protocols</strong>: Web APIs can use protocols such as HTTP, HTTPS, and TCP/IP to facilitate communication between clients and servers.</li><li><strong>Flexible Interface</strong>: Web APIs expose various functionalities of the application, including CRUD operations, authentication, authorization, and more.</li><li><strong>No Specific Architecture</strong>: Unlike REST, Web APIs do not have to follow a specific architectural style, allowing for more flexibility in their design and implementation.</li></ul><h3>SOAP</h3><p><strong>SOAP (Simple Object Access Protocol)</strong> is a protocol for exchanging structured information in web services. Unlike REST, which is an architectural style, SOAP is a strictly defined protocol. Here are some distinctive characteristics of SOAP:</p><ul><li><strong>Protocol-Based</strong>: SOAP follows a strict standard for sending messages. It relies on <strong>XML</strong> as the format for both requests and responses, which makes it more rigid.</li><li><strong>Built-In Security and Transactions</strong>: SOAP supports features like <strong>WS-Security</strong> and <strong>ACID</strong>-compliant transactions, making it suitable for applications that need strong security and reliability.</li><li><strong>Verbose Payload</strong>: SOAP messages tend to be large because they are encoded in XML, which can make SOAP less efficient than REST.</li><li><strong>Transport Flexibility</strong>: SOAP can work over different protocols, including <strong>HTTP</strong>, <strong>SMTP</strong>, <strong>FTP</strong>, and <strong>TCP</strong>, which gives it flexibility in diverse environments.</li><li><strong>Platform and Language Independence</strong>: SOAP is designed to be platform-agnostic and can be used across different programming languages and environments.</li><li><strong>WSDL</strong>: SOAP uses <strong>WSDL (Web Services Description Language)</strong> to describe the available operations and their parameters, ensuring a standardized interface between services.</li><li><strong>Supports Different Data Types</strong>: SOAP can handle complex data types, such as text, numbers, dates, and binary data, which makes it highly versatile.</li><li><strong>Digital Signatures and Encryption</strong>: SOAP includes support for <strong>digital signatures</strong> and <strong>encryption</strong> to ensure secure communication.</li></ul><p>SOAP is well-suited for large-scale, enterprise applications where strong security and formal messaging standards are necessary, though it is generally more complex than REST.</p><h3>REST vs Web API vs SOAP:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*UpMYW7SSnt7PpqWw4dup0g.png" /></figure><h3>When to Use Each</h3><ul><li><strong>REST API</strong>: Use REST when you need a lightweight, flexible solution that is easy to work with. REST is particularly effective for web and mobile applications that require high performance, scalability, and ease of integration. If your application involves simple CRUD operations (Create, Read, Update, Delete) and you want to use a modern JSON format, REST is the ideal choice.</li><li><strong>Web API</strong>: The term Web API can encompass various protocols and architectural styles. Use a Web API if you need a general-purpose solution that can leverage different underlying technologies, such as REST, SOAP, or GraphQL. This makes Web APIs suitable for a wide range of web-based interactions that do not strictly adhere to one particular style.</li><li><strong>SOAP</strong>: Use SOAP when enterprise-level security and reliability are essential, particularly in domains such as financial services, healthcare, and government systems. SOAP is designed for highly secure environments, supports ACID transactions, and provides a well-defined messaging structure. Its built-in features, such as WS-Security, digital signatures, and encryption, make it the best choice for applications requiring robust security and formal standards.</li></ul><p>Finally, REST is popular for its simplicity and scalability, SOAP is chosen for its robustness and security in enterprise settings, and Web API is a general concept that covers multiple approaches. Depending on your specific needs — whether they are performance, flexibility, or security — there is an appropriate API model that will help you achieve your goals.</p><p>Ultimately, selecting the right API approach requires a clear understanding of your application’s requirements and constraints. Each API type has its strengths and is suited for different situations, making it essential to evaluate your use case carefully before making a decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=279bd3bf7956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Encrypt Sensitive Data with Python/Django]]></title>
            <link>https://anilkumarvalluru.medium.com/how-to-encrypt-sensitive-data-with-python-django-ef592aa1a6a9?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef592aa1a6a9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 11:38:39 GMT</pubDate>
            <atom:updated>2023-11-08T11:38:39.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*HXj_8LHTjoDizvpS" /></figure><p>In today’s digital age, data security is paramount. With the increasing volume of sensitive information stored online, businesses and developers must take every precaution to protect their user’s <strong>confidential data</strong>. One effective way to enhance data security is through encryption, and in this article, we’ll explore how to encrypt confidential data using Django, a popular Python web framework.</p><h3>Why Encrypt Confidential Data?</h3><p>Before we dive into the technical aspects, let’s briefly discuss why encrypting confidential data is so important:</p><ol><li><strong>Protection against Unauthorized Access</strong>: Encryption transforms data into an unreadable format for unauthorized users, ensuring that even if a breach occurs, the data remains protected.</li><li><strong>Compliance with Regulations</strong>: Many industries and regions have stringent data protection regulations (such as GDPR or HIPAA). Encryption is often a requirement to comply with these regulations.</li><li><strong>Safe Data Transmission</strong>: When transmitting data over the internet, encryption ensures that it cannot be intercepted and deciphered by malicious actors.</li><li><strong>Builds Trust</strong>: Demonstrating a commitment to data security can enhance trust and reputation with customers, partners, and stakeholders.</li></ol><h3>Using Django for Data Encryption</h3><p>Django provides a robust framework for building web applications, and it offers several tools and libraries that make data encryption relatively straightforward. Here’s how we can get started:</p><h3>1. Generate a Strong Secret Key</h3><p>In a production environment, the security of our encryption system depends on a strong secret key. The Fernet encryption algorithm, commonly used in python, provides a convenient method for generating such keys:</p><pre>from cryptography.fernet import Fernet<br>key = Fernet.generate_key()</pre><p>This will create a random <strong>32-byte</strong> (256-bit) secret key. Generate this key once and keep it securely stored. We can then use this secret key to encrypt and decrypt data using the Fernet algorithm.</p><h3>2. Store the Secret Key Securely</h3><p>Store the secret key in a secure location that is not part of the source code or version control system. Common practices include:</p><ul><li><strong>Environment Variables</strong>: Set the secret key as an environment variable on the production server(s).</li><li><strong>Configuration File</strong>: Store the secret key in a configuration file that is read by the application. This file should not be committed to the version control system.</li><li><strong>Secret Management Service</strong>: Consider using a secret management service like AWS Secrets Manager, HashiCorp Vault, or similar services.</li></ul><h3>3. Define an Encryption Helper</h3><p>Create a helper module for encryption this module should contain functions to encrypt and decrypt sensitive data using the secret key.</p><p>Here’s a simplified example:</p><pre>from cryptography.fernet import Fernet<br><br># Load the secret key securely<br>SECRET_KEY = get_secret_key_from_secure_location()<br># Create an instance of the Fernet cipher<br>cipher_suite = Fernet(SECRET_KEY)<br>def encrypt_data(data):<br>    encrypted_data = cipher_suite.encrypt(data.encode())<br>    return encrypted_data<br>def decrypt_data(encrypted_data):<br>    decrypted_data = cipher_suite.decrypt(encrypted_data).decode()<br>    return decrypted_data</pre><h3>4. Encrypt and Decrypt Data</h3><p>Suppose we are developing an e-commerce platform where customers can store their <strong>card</strong> information for future purchases. To ensure the highest level of security and comply with Payment Card Industry Data Security Standard (PCI DSS) requirements, we need to encrypt and protect this sensitive data.</p><p>Here’s how we can implement encryption for card information in a Django model:</p><pre>from django.db import models<br>from .helper import encrypt_data, decrypt_data<br><br>class Customer(models.Model):<br>    name = models.CharField(max_length=100)<br>    encrypted_card_number = models.BinaryField()  # Field to store the encrypted card number<br>    encrypted_expiry_date = models.BinaryField()   # Field to store the encrypted card expiry date<br>    def set_card_info(self, card_number, expiry_date):<br>        # Encrypt and save the card information when setting it<br>        self.encrypted_card_number = encrypt_data(card_number)<br>        self.encrypted_expiry_date = encrypt_data(expiry_date)<br>    def get_card_info(self):<br>        # Decrypt and return the card information when needed<br>        card_number = decrypt_data(self.encrypted_card_number)<br>        expiry_date = decrypt_data(self.encrypted_expiry_date)<br>        return card_number, expiry_date</pre><p>In the above model, we have a <strong><em>Customer </em></strong>class with a name field and two <strong><em>binary fields, encrypted_card_number</em></strong> and <strong><em>encrypted_expiry_date</em></strong>, which will store the encrypted card number and expiry date, respectively.</p><p>Now, we can use the Customer model to securely store and retrieve customer payment card information:</p><pre># Storing a customer&#39;s card information<br>customer = Customer(name=&quot;Alice&quot;)<br>customer.set_card_info(&quot;4111 1111 1111 1111&quot;, &quot;12/25&quot;)  # Encrypts and stores card info<br>customer.save()<br><br># Retrieving a customer&#39;s card information<br>retrieved_customer = Customer.objects.get(name=&quot;Alice&quot;)<br>card_number, expiry_date = retrieved_customer.get_card_info()  # Decrypts and returns card info</pre><p>By encrypting payment card information using the above methods, we will ensure that sensitive data is stored securely in our e-commerce application, protecting both the customers and business from potential data breaches and complying with PCI DSS requirements.</p><h3>5. Key Rotation and Backup</h3><p>Implement a key rotation policy in the <strong>production</strong> environment. Periodically change the secret key to enhance security and reduce the risk of a compromised key leading to data exposure. When we rotate the key, ensure that we need to decrypt and re-encrypt data using the new key.</p><p>Additionally, establish a robust backup and recovery plan for the secret key. Losing the secret key can result in data loss, so having procedures in place to securely recover or regenerate the key is essential.</p><p>By following these best practices, we can maintain the security and integrity of encrypted data in a production environment while also ensuring that we can recover from potential key-related issues. Data security should remain a top priority as we continue to build and scale the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef592aa1a6a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles through Django]]></title>
            <link>https://anilkumarvalluru.medium.com/understanding-solid-principles-through-django-b05930a606ce?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b05930a606ce</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[principles]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 16:14:34 GMT</pubDate>
            <atom:updated>2023-10-31T16:14:34.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*yMtTPFwHK9aaGTyn" /><figcaption>SOLID Principles in Django</figcaption></figure><p>SOLID principles are essential guidelines that help developers build software that is easy to maintain, understand, and expand. Today, I’ll break down these principles using Django, a web framework built with Python, and provide simple examples to bring each one to life.</p><h3>S — Single Responsibility Principle (SRP)</h3><p>The Single Responsibility Principle (SRP) tells us that each piece of your software should do one thing only.</p><p>In the world of Django, this might mean that each part of your software, like a ‘<strong>model</strong>’ or a ‘<strong>view</strong>’, should do one thing only.</p><p>Here’s an example using Django’s models:</p><pre>class User(models.Model):<br>    ...<br>    def calculate_age(self):<br>        # calculating the user&#39;s age based on their birthday.</pre><p>In this example, the <strong>User </strong>model’s only job is to handle user information. The function <em>calculate_age </em>only does one thing too: it calculates the age of a user.</p><h3>O — Open/Closed Principle (OCP)</h3><p>The Open/Closed Principle (OCP) suggests that your software should be open to being extended (or added to), but closed to modification. This means that when you want to add new features, you shouldn’t have to change existing code.</p><p>Let’s consider that we have a Django model for an online store that calculates the price of a product:</p><pre>class Product(models.Model):<br>    name = models.CharField(max_length=200)<br>    price = models.DecimalField(max_digits=5, decimal_places=2)<br><br>    def get_price(self):<br>        return self.price</pre><p>Suppose you want to introduce a new type of product, a ‘<strong>DiscountedProduct</strong>’, where the price calculation differs — it must account for a discount.</p><p>A naive approach would involve modifying the existing Product class and adding conditional logic in the <em>get_price </em>method. But this approach would violate the OCP because we’re modifying existing code.</p><p>Instead, we should extend the existing code. Here’s how to do it:</p><pre>class DiscountedProduct(Product):<br>    discount_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=0.0)<br><br>    def get_price(self):<br>        original_price = super().get_price()<br>        discounted_price = original_price * (1 - self.discount_percentage / 100)<br>        return discounted_price.quantize(Decimal(&#39;0.00&#39;), rounding=ROUND_DOWN)</pre><p>Here we created a new model <strong>DiscountedProduct </strong>that extends our existing Product model. We’ve added a new field for <em>discount_percentage </em>and overridden the <em>get_price</em> method to account for the discount.</p><p>This way, we’ve added new functionality (discounted products) without changing the existing <strong>Product </strong>model code, adhering to the Open/Closed Principle.</p><h3>L — Liskov Substitution Principle (LSP)</h3><p>The Liskov Substitution Principle (LSP) says that you should be able to replace a parent class (or model) with its child class without causing problems.</p><p>For example, in Django:</p><pre>class Vehicle(models.Model):<br>    def can_fly(self):<br>        return False<br><br>class Airplane(Vehicle):<br>    def can_fly(self):<br>        return True</pre><p>In this example, <strong>Vehicle </strong>is the parent model, and <strong>Airplane </strong>is the child model. The child model can replace the parent model without causing problems, which is exactly what the LSP recommends.</p><h3>I — Interface Segregation Principle (ISP)</h3><p>The Interface Segregation Principle (ISP) tells us that we should not force our software to rely on parts it does not use. Instead of making one large piece that does everything, we should make several small pieces that do specific things.</p><p>Let’s consider that we have a Django model called <strong>User model</strong>, and we want to create forms to handle user registration and user profile updates.</p><pre>class User(models.Model):<br>    username = models.CharField(max_length=200)<br>    email = models.EmailField()<br>    password = models.CharField(max_length=128)    <br>    phone_number = models.CharField(max_length=15, blank=True, null=True)<br>    address = models.CharField(max_length=300, blank=True, null=True)</pre><p>Instead of creating one large form that handles every field (username, email, password, phone number, address), we create two different forms each having specific fields:</p><pre>class UserRegistrationForm(forms.ModelForm):<br>    password = forms.CharField(widget=forms.PasswordInput)<br>    class Meta:<br>        model = User<br>        fields = [&#39;username&#39;, &#39;email&#39;, &#39;password&#39;]<br><br>class UserProfileForm(forms.ModelForm):<br>    class Meta:<br>        model = User<br>        fields = [&#39;phone_number&#39;, &#39;address&#39;]</pre><p>Here <strong>UserRegistrationForm </strong>only deals with <em>username, email </em>and <em>password</em> fields which are necessary for registering a new user, and <strong>UserProfileForm </strong>deals with <em>phone number</em> and <em>address fields</em> which are needed for updating user profile information.</p><h3>D — Dependency Inversion Principle (DIP)</h3><p>Finally, the Dependency Inversion Principle (DIP) an important aspect of a well-structured object-oriented design. It proposes that high-level modules should not depend on low-level modules; both should depend on abstractions. Also, abstractions should not depend on details; details should depend on abstractions.</p><p>While in Python we don’t have interfaces as in other languages like Java, we can still apply this principle using different techniques. One of them in Django could be through the use of signals.</p><p>Let’s say we have a Product model and we want to log every time a product is saved. A naive approach would be to override the save method and include the logging code there. But this would create a dependency of our Product model on the logging system. Instead, we could use Django signals to decouple these responsibilities.</p><pre>class Product(models.Model):<br>    name = models.CharField(max_length=200)<br>    price = models.DecimalField(max_digits=5, decimal_places=2)</pre><p>Next, we create our <strong>signal </strong>receiver function, which listens for the <em>post_save </em>signal from the Product model:</p><pre>from django.db.models.signals import post_save<br>from django.dispatch import receiver<br>import logging<br>logger = logging.getLogger(__name__)<br><br>@receiver(post_save, sender=Product)<br>def log_product_save(sender, instance, **kwargs):<br>    logger.info(f&#39;Product &quot;{instance.name}&quot; has been saved.&#39;)</pre><p>Now, whenever a <strong>Product </strong>is saved, the <em>log_product_save</em> function will be called, and the save operation will be logged. Here the logging system depends on the Product model, not the other way around.</p><p>That’s it! These are the <strong>SOLID</strong> principles, explained simply with Django examples. These principles might seem challenging at first, but if you take them one at a time, you’ll find that they can make your code much easier to understand, maintain, and expand. Remember, the best code is a combination of following these principles, using common patterns, and a bit of common sense.</p><p>I hope you found this explanation helpful. Now, I would love to hear from you. What are your thoughts on the <strong>SOLID principles</strong>? How have you applied them in your Django projects? Please share your experiences, thoughts, and questions in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b05930a606ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Types of Slowly Changing Dimensions (SCD)]]></title>
            <link>https://anilkumarvalluru.medium.com/different-types-of-slowly-changing-dimensions-scd-eb83da61cb73?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb83da61cb73</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 05:56:50 GMT</pubDate>
            <atom:updated>2023-10-18T05:56:50.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*ivI37AqaeeW39ZsM" /><figcaption>Different Types of Slowly Changing Dimensions (SCD Types)</figcaption></figure><p>In database management and data warehousing, <strong>Slowly Changing Dimensions (SCD)</strong> play a crucial role in capturing <strong>historical data</strong> and preserving the integrity of historical records. <strong>SCD</strong>’s are used to track changes in dimension attributes over time, enabling analysts and decision-makers to analyze data trends accurately.</p><h3>SCD Type 1:</h3><p>This is the simplest form of handling dimension changes. In this approach, when a change occurs in an attribute, the existing record is<strong> directly updated</strong>, effectively overwriting the <strong>old data</strong> with the new value. This method <strong>does not maintain</strong> historical information and is suitable when historical data is not critical or not required.</p><p>E.g.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*0FB0z4jEDsCp4LsY" /></figure><p>Product Dimension table that stores information about various products in an electronics store</p><p>Suppose the price of the Laptop was changed to <strong>850</strong> on <strong>2023–07–15</strong>. After updating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*ySmTE8y-A0pesq2O" /></figure><p>Using <strong>SCD Type 1</strong>, the existing record for the Laptop is <strong>directly updated</strong> with the new price and the updated Effective Date. <strong>No historical information</strong> is preserved in this method, and the old price is effectively replaced with the new one.</p><h3>SCD Type 2:</h3><p>SCD Type 2 maintains historical versions of dimension records by creating <strong>new rows</strong> for each change, effectively creating a <strong>versioned history</strong>. This approach ensures that historical data remains intact and can be used for <strong>auditing or trend</strong> analysis.</p><p>E.g.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/0*BW2sf8YHhnL3Vgor" /></figure><p>Employee Dimension table that maintains data related to employees in a company</p><p>When John Doe switches from the Sales department to Marketing on 2023–07–01, a new row is added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*XMrQi3TxvgL5Gb84" /></figure><p>Initially, John Doe is associated with the Sales department, starting from 1st January 2022. When he transitions to the Marketing department on 1st July 2023, instead of overwriting the existing record, SCD Type 2 creates a new row for John Doe with the updated Department and a NULL value for the End Date, indicating that the employee is still associated with the company.</p><p>This approach allows us to keep track of <strong>historical information</strong>, providing a <strong>versioned history</strong> of employee data and facilitating historical <strong>reporting and auditing</strong>.</p><h3>SCD Type 3:</h3><p>SCD Type 3 keeps track of limited historical information by maintaining attributes as <strong>separate columns</strong>. It allows us to store a <strong>limited number of changes</strong> and is commonly used when maintaining a few previous versions is sufficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*TqMdiyhMmJP4e793" /></figure><p>Employee Dimension table that maintains data related to employees in a company</p><p>When Jane Smith switches departments from Marketing to Sales on 1st July 2023:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*_YwZL7Jp206nb3l-" /></figure><p>Initially, Jane Smith joined the company and was assigned to the Marketing department on 15th March 2023. However, on 1st July 2023, she switched departments to Sales.</p><p>By implementing the <strong>SCD Type 3</strong> approach, we can efficiently track <strong>limited historical changes</strong> for dimension attributes without creating multiple rows for each alteration. This approach strikes a balance between keeping historical information and avoiding an excessive number of records in the dimension table, making it useful for scenarios where a few previous versions are sufficient for analysis and reporting purposes.</p><h3>SCD Type 4:</h3><p>In SCD Type 4 there is no change to our existing table here, we simply update the record as if a <strong>Type 1</strong> change had occurred. However, we simultaneously maintain a history table to keep track of these changes. Separating the historical data makes your dimensions smaller and therefore reduces complexity and improves performance if the majority of uses only need the current value. However, if you do require historical values, this structure adds complexity and data redundancy overheads.</p><p>Finally, each type of Slowly Changing Dimension has its unique characteristics and use cases. SCD Type 1 is suitable when historical data is not necessary, Type 2 is preferred when maintaining a versioned history is vital, and Type 3 is beneficial when tracking a limited number of changes efficiently.</p><p>By understanding these different approaches, software architects and data professionals can implement the appropriate Slowly Changing Dimension strategy based on the specific requirements of their projects. This ensures that historical data is accurately preserved and made available for data analysis, decision-making, and historical reporting.</p><p>#database #datawarehouse #oracle #mysql #sql #scd #types #softwareengineering #software #softwaredevelopment #databasedesign #datamanagement</p><p><em>Thank you for taking the time to read this! I sincerely hope that your time was well-spent.</em></p><p><em>Before you go be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb83da61cb73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing The Right ID Strategy: Auto-Increment, UUID, ULID or Snowflake ID]]></title>
            <link>https://anilkumarvalluru.medium.com/choosing-the-right-id-strategy-auto-increment-uuid-ulid-or-snowflake-id-e21fe24af55f?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e21fe24af55f</guid>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 06:37:15 GMT</pubDate>
            <atom:updated>2023-10-10T06:37:15.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*8p-O5oC8xGQrcN3D" /></figure><p>When it comes to databases, the unique identification of records is a critical aspect of design. There are a multitude of strategies out there, and the best one for your application depends heavily on your use case, size of your application, and the relationships between your data entities. In this post, we’ll take a look at four common ID strategies: Auto-increment, UUID, ULID, and Snowflake ID.</p><h3>Auto-Increment IDs:</h3><p>The simplest form of ID generation is Auto-incrementing IDs. Auto-Increment IDs are the old faithful of database identifiers. Each new record gets an ID that’s one higher than the record before it. It’s simple, efficient, and easy to implement. But, it’s not without its downsides. Auto-increment IDs can reveal sensitive information about your database, like how many records you have, and the rate of new records. Also, it might become a problem in distributed systems where multiple instances need to create unique IDs.</p><p>This is how auto-increment IDs would look in a basic users table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/0*NKF2ISHP0MbB9nml" /><figcaption>Auto-Increment IDs</figcaption></figure><p><strong>Pros</strong>:</p><ul><li><strong>Simplicity</strong>: They are easy to implement and understand. No complex logic.</li><li><strong>Efficiency</strong>: Auto-increment IDs are light on storage and provide quick retrieval times.</li></ul><p><strong>Cons</strong>:</p><ul><li><strong>Scalability</strong>: They can run into concurrency issues in distributed systems and lead to potential collisions.</li><li><strong>Security</strong>: Since they’re predictable, they can lead to potential security breaches especially in public-facing APIs.</li></ul><h3>Universally Unique Identifier (UUID)</h3><p>UUID, or Universally Unique Identifier, addresses some of these issues. Each ID is a random 128-bit number, and it’s so unique that you can practically guarantee no collisions, even across multiple databases. However, randomness leads to its own problems. In some databases, random UUIDs can lead to performance issues due to constant reordering of records.</p><p>Here’s how a users table might look with UUIDs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*-7dXZqm2qaWQQbPW" /><figcaption>Universally Unique Identifier (UUID)</figcaption></figure><p><strong>Pros:</strong></p><ul><li><strong>Universality</strong>: They’re ideal for distributed systems because they’re always unique.</li><li><strong>Security</strong>: Unpredictability provides security against ID guessing.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Efficiency</strong>: Larger storage space and slower retrieval times due to non-sequential nature.</li><li><strong>Readability</strong>: Not user-friendly because of their length and complexity.</li></ul><h3>Universally Unique Lexicographically Sortable Identifier (ULID)</h3><p>ULID, or Universally Unique Lexicographically Sortable Identifier, tries to strike a balance. The first part of a ULID is a timestamp, the second part is random. This makes them sortable like auto-increment IDs, but still unique like UUIDs. Yet, there’s still the potential for collisions within the same millisecond.</p><p>Here’s an example of ULIDs in a users table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*AVTYQ_CzCQhc4EFu" /><figcaption>Universally Unique Lexicographically Sortable Identifier (ULID)</figcaption></figure><p><strong>Pros:</strong></p><ul><li><strong>Chronological Ordering</strong>: Useful where time-based sorting of IDs is beneficial.</li><li><strong>Uniqueness</strong>: Like UUIDs, ULIDs provide uniqueness which is suitable in distributed systems.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Efficiency</strong>: Larger storage requirement and slower retrieval times.</li><li><strong>Complexity</strong>: More complex to implement than auto-increment IDs.</li></ul><h3>Snowflake IDs</h3><p>Lastly, we have Snowflake ID, originally developed by Twitter. It’s a 64-bit ID where a timestamp is combined with a machine identifier and a sequence number. This practically eliminates collisions and maintains a rough timeline of creation. However, it’s more complex to implement and has its own operational constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*VgnrgqMPwt3JkcUu" /><figcaption>Snowflake IDs</figcaption></figure><p><strong>Pros:</strong></p><ul><li><strong>Chronological Ordering</strong>: Can be sorted chronologically like ULIDs.</li><li><strong>Scalability</strong>: Uniqueness and distributed nature makes it ideal for larger distributed systems.</li><li><strong>Efficiency</strong>: They are more efficient than UUIDs or ULIDs due to less storage requirement.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Complexity</strong>: Implementation is more complex than auto-increment IDs or UUIDs.</li><li><strong>System Limits</strong>: The system needs synchronization and there’s a limit on number of IDs that can be generated per millisecond.</li></ul><p>Finally, choosing an ID strategy depends on your application’s requirements. Auto-increment IDs can suffice for simple, non-distributed applications. For distributed systems where global uniqueness is crucial, <strong><em>UUIDs, ULIDs, or Snowflake ID</em></strong>s might be the best fit. Among these, if chronological sorting is important, <strong><em>ULID</em></strong>s and <strong><em>Snowflake ID</em></strong>s are preferred.</p><p>Remember, the right ID system can enhance performance, security, and maintainability of your application. It is worth spending the time to choose and implement the most appropriate ID strategy for your needs.</p><p><em>If you found this story helpful, please give it a clap and share it within your network.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e21fe24af55f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing and Implementing Custom Fields in Django: Creating Dynamic Data Models]]></title>
            <link>https://anilkumarvalluru.medium.com/designing-and-implementing-custom-fields-in-django-creating-dynamic-data-models-b57f9f935467?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b57f9f935467</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[custom-data]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 06:32:22 GMT</pubDate>
            <atom:updated>2023-10-09T06:32:22.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DET3b-VNQ7ocuI_vb9PnMg.png" /></figure><p>Custom fields are a powerful feature that enables users to tailor their applications to their unique business requirements. By allowing users to define additional attributes such as labels, data types, validation rules, and styles, custom fields provide a flexible solution for storing and managing data. In this article, we’ll explore how to create custom fields in a Django application, empowering you to design adaptable data models that cater to your application’s specific needs.</p><h3>1. Designing the Custom Field Model</h3><p>Implementing custom fields is to create a <strong>CustomField</strong> model that stores the user-defined fields and their attributes. This model will include properties like <strong><em>field_name, field_type, related_model, label, validation, and style</em></strong>.</p><pre>from django.db import model<br><br>class CustomField(models.Model):<br>    FIELD_TYPES = [<br>        (&quot;text&quot;, &quot;Text&quot;),<br>        (&quot;number&quot;, &quot;Number&quot;),<br>        (&quot;date&quot;, &quot;Date&quot;),<br>        (&quot;boolean&quot;, &quot;Boolean&quot;),<br>    ]<br>    field_name = models.CharField(max_length=255)<br>    field_type = models.CharField(max_length=50, choices=FIELD_TYPES)<br>    related_model = models.CharField(max_length=255)<br>    label = models.CharField(max_length=255, null=True, blank=True)<br>    validation = models.JSONField(null=True, blank=True)<br>    style = models.JSONField(null=True, blank=True)</pre><h3>2. Creating the Custom Field Values Model</h3><p>Next, we need another model called <strong><em>CustomFieldValue</em></strong> to store the actual data of the custom fields.</p><pre>from django.db import model<br>from django.contrib.contenttypes.models import ContentType<br><br>class CustomFieldValue(models.Model):<br>    custom_field = models.ForeignKey(CustomField, <br>                                     on_delete=models.CASCADE)<br>    object_id = models.PositiveIntegerField()<br>    content_type = models.ForeignKey(ContentType, <br>                                     on_delete=models.CASCADE)<br>    value = models.TextField()<br><br>    class Meta:<br>        unique_together = (&#39;custom_field&#39;, &#39;content_type&#39;, &#39;object_id&#39;)</pre><h3>3. Extending Django Models with Custom Fields</h3><p>To integrate custom fields with existing Django models, we’ll create a mixin called <strong>CustomFieldMixin</strong>, which can be added to any Django model:</p><pre>from django.contrib.contenttypes.fields import GenericRelation<br><br>class CustomFieldMixin:<br>    custom_field_values = GenericRelation(CustomFieldValue)<br><br>    def set_custom_field_value(self, field_name, value):<br>        custom_field = CustomField.objects.get(<br>            field_name=field_name, related_model=self.__class__.__name__<br>        )<br>        CustomFieldValue.objects.update_or_create(<br>            custom_field=custom_field,<br>            content_type=ContentType.objects.get_for_model(self),<br>            object_id=self.pk,<br>            defaults={&quot;value&quot;: value},<br>        )<br><br>    def get_custom_field_value(self, field_name):<br>        custom_field = CustomField.objects.get(<br>            field_name=field_name, related_model=self.__class__.__name__<br>        )<br>        custom_field_value = CustomFieldValue.objects.get(<br>            custom_field=custom_field,<br>            content_type=ContentType.objects.get_for_model(self),<br>            object_id=self.pk,<br>        )<br>        return custom_field_value.value</pre><h3>4. Implementing Custom Field Validation and Styling</h3><p>Before illustrating custom field validation and styling, let’s create a sample model called Contact that includes custom fields by extending the <strong>CustomFieldMixin</strong>:</p><pre>from django.db import model<br>from .custom_fields import CustomFieldMixin<br><br>class Contact(CustomFieldMixin, models.Model):<br>    first_name = models.CharField(max_length=255)<br>    last_name = models.CharField(max_length=255)<br>    email = models.EmailField(max_length=255)</pre><p>Now, to enforce validation rules and apply custom styles to your custom fields, you can utilize the validation and style attributes of the <strong>CustomField</strong> model when rendering your forms or processing form submissions.</p><p>For example, let’s create a form for the Contact model:</p><pre>from django import forms<br>from django.forms import ValidationError<br>from .models import Contact, CustomField<br><br>class ContactForm(forms.ModelForm):<br>    class Meta:<br>        model = Contact<br>        fields = [&quot;first_name&quot;, &quot;last_name&quot;, &quot;email&quot;]<br><br>    def __init__(self, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        custom_fields = CustomField.objects.filter(related_model=&quot;Contact&quot;)<br><br>        for custom_field in custom_fields:<br>            self.fields[custom_field.field_name] = forms.CharField(<br>                label=custom_field.label,<br>                required=False,<br>                widget=forms.TextInput(attrs=custom_field.style),<br>            )<br><br>    def clean(self):<br>        cleaned_data = super().clean()<br>        custom_fields = CustomField.objects.filter(related_model=&quot;Contact&quot;)<br><br>        for custom_field in custom_fields:<br>            value = cleaned_data.get(custom_field.field_name)<br>            validation = custom_field.validation<br>            # Validate the custom field value based on the validation rules<br>            if validation:<br>                # Example: Check if the value is required<br>                if validation.get(&quot;required&quot;) and not value:<br>                    self.add_error(<br>                        custom_field.field_name,<br>                        ValidationError(&quot;This field is required.&quot;),<br>                    )<br>        return cleaned_data<br><br>  def save(self):<br>        instance = super().save()<br>        custom_fields = CustomField.objects.filter(related_model = &quot;Contact&quot;)<br><br>        for custom_field in custom_fields:<br>            field_name = custom_field.field_name<br>            field_value = self.cleaned_data.get(field_name)<br>            instance.set_custom_field_value(field_name, field_value)<br><br>        return instance</pre><p>In this <strong>ContactForm</strong>, we first render the default fields (<em>first_name, last_name, and email</em>). Then, we fetch the custom fields related to the Contact model and add them to the form. The custom field’s label and style attributes are applied to the form field and custom validation logic to the clean method. We iterate through the custom fields and enforce the validation rules defined in the validation attribute of the <strong>CustomField</strong> model.</p><h3>5. Searching and Filtering Custom Fields</h3><p>To enable searching and filtering custom field data, you can use <strong>Django’s Q</strong> objects and <strong>annotate()</strong> function to perform complex lookups. For example, let’s say you want to find all contacts with a custom field “<strong><em>company</em></strong>” containing the value <em>“ABC Corporation”:</em></p><pre>from django.db.models import Q, F<br>from django.contrib.contenttypes.models import ContentType<br>from .models import Contact, CustomFieldValue, CustomField<br><br>content_type = ContentType.objects.get_for_model(Contact)<br><br>company_field = CustomField.objects.get(<br>    field_name=&quot;company&quot;, <br>    related_model=&quot;Contact&quot;<br>    )<br><br>contacts = Contact.objects.annotate(<br>    company_value=CustomFieldValue.objects.filter(<br>        Q(custom_field=company_field) &amp;<br>        Q(content_type=content_type) &amp;<br>        Q(object_id=F(&quot;id&quot;))<br>    ).values(&quot;value&quot;)<br>).filter(company_value=&quot;ABC Corporation&quot;)</pre><h3>6. Bulk Editing Custom Fields</h3><p>To update custom fields for multiple records at once, you can use Django’s update() method to perform bulk updates efficiently. For instance, let’s say you want to update the “<strong><em>company</em></strong>” custom field for all contacts with the email domain <strong><em>“example.com”</em></strong>:</p><pre>from django.db.models import F<br>from django.contrib.contenttypes.models import ContentType<br>from .models import Contact, CustomFieldValue, CustomField<br><br>content_type = ContentType.objects.get_for_model(Contact)<br><br>company_field = CustomField.objects.get(<br>    field_name=&quot;company&quot;, <br>    related_model=&quot;Contact&quot;<br>)<br><br>contact_ids = Contact.objects.filter(<br>    email__icontains=&quot;@example.com&quot;<br>    ).values_list(<br>        &quot;id&quot;, flat=True<br>)<br><br>CustomFieldValue.objects.filter(<br>    custom_field=company_field, <br>    content_type=content_type, <br>    object_id__in=contact_ids<br>).update(value=&quot;New Company Name&quot;)</pre><h3>Advantages:</h3><p>1. <strong>Flexibility</strong>: Custom fields provide a flexible solution for storing and managing data, allowing users to define additional attributes such as labels, data types, validation rules, and styles. This enables you to tailor your application to meet unique business requirements.</p><p>2. <strong>Dynamic Data Models</strong>: Custom fields empower you to design adaptable data models that cater to your application’s specific needs. You can easily extend existing Django models with custom fields, making your application more extensible and maintainable.</p><p>3. <strong>Custom Validation and Styling</strong>: With custom fields, you can enforce validation rules and apply custom styles to your fields, enhancing the user experience and ensuring data integrity.</p><h3>Disadvantages:</h3><p>1. <strong>Complexity</strong>: Implementing custom fields can increase the complexity of your application, as you need to manage the additional models, forms, and logic required for custom fields. This may make your codebase harder to maintain and understand.</p><p>2. <strong>Potential Performance Issues</strong>: If caching is not implemented correctly, custom fields can lead to performance issues, especially when dealing with large datasets. Proper caching strategies should be employed to mitigate these issues.</p><p>3. <strong>Database Migrations</strong>: When adding or modifying custom fields, you may need to create and apply database migrations. This can be time-consuming and may introduce the risk of data loss or corruption if not handled carefully.</p><h3>Conclusion:</h3><p>Finally, custom fields offer a powerful and flexible solution for designing dynamic data models and catering to unique business requirements in Django applications. By implementing custom fields, you can create a highly extensible and maintainable application while providing an enhanced user experience with custom validation and styling.</p><p>However, it’s essential to consider the potential complexity and performance implications when implementing custom fields. By carefully managing your codebase, implementing effective caching strategies, and handling database migrations properly, you can harness the full potential of custom fields while minimizing the drawbacks.</p><p>Overall, custom fields are an invaluable tool for creating adaptable, extensible, and user-friendly Django applications that meet the ever-evolving needs of your users and your business.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b57f9f935467" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Row and Column-Level Security in Django]]></title>
            <link>https://anilkumarvalluru.medium.com/implementing-row-and-column-level-security-in-django-37fe47b0c563?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/37fe47b0c563</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 09:15:56 GMT</pubDate>
            <atom:updated>2023-10-06T09:15:56.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ImZlHk2TXHDfyzYEih0emw.png" /></figure><p>Data security is a critical aspect of any web application, and ensuring that sensitive information is protected. <strong>Django</strong>, a popular <strong>Python</strong> web framework, offers robust features for building secure applications. In this article, we will explore how Django can be leveraged to implement <strong>row</strong> and <strong>column-level</strong> security, providing fine-grained access control to data within a database. We will delve into the concepts of row-level and column-level security, discuss their importance, and provide practical examples of their implementation using <strong>Django’s</strong> built-in mechanisms.</p><p><strong>Understanding Row-Level Security:</strong></p><p>Row-level security involves controlling access to individual rows of data in a database table based on specific conditions or rules. This ensures that each user or role can only access the data they are authorized to view or modify. By implementing row-level security, sensitive information can be protected from unauthorized access or accidental exposure.</p><p><strong>Implementing Row-Level Security in Django:</strong></p><p>Django provides several built-in mechanisms for implementing row-level security:</p><ol><li><strong>Custom QuerySets</strong>: Django’s QuerySets allow you to define custom filters and queries to retrieve specific rows of data based on user-defined conditions. By utilizing filters and annotations, you can limit the data returned to users based on their access privileges. For example, you can filter data based on the user’s department or organizational hierarchy.</li><li><strong>Middleware</strong>: Django middleware sits between the web server and the framework, allowing you to intercept requests and apply security rules. By implementing custom middleware, you can perform additional checks on the requested data, ensuring that only authorized users can access or modify specific rows.</li><li><strong>Django Guardian</strong>: Django Guardian is a powerful third-party library that provides object-level permissions in Django. It allows you to define per-object permissions, granting or revoking access to individual rows based on user roles or specific conditions. This library seamlessly integrates with Django’s authentication system and provides a granular level of control over data access.</li></ol><p><strong>Column-Level Security in Django:</strong></p><p>Column-level security focuses on controlling access to specific columns within a database table. This level of security is particularly useful when certain columns contain sensitive or confidential data that needs to be restricted to specific user roles or groups.</p><p>Django’s Model Field Permissions feature allows you to define specific permissions for individual model fields. By assigning read and write permissions to columns, you can ensure that only authorized users can view or modify specific data within a row. This approach is helpful when different user roles require varying levels of access to different columns in a table.</p><p><strong>Examples</strong>:</p><p>Let’s consider a practical example of implementing row and column-level security in Django:</p><p><strong>a. Row-Level Security:</strong></p><p>Suppose we have an Employee model with a “<strong>department</strong>” field, and we want to restrict access to employee records based on the user’s department. By implementing custom <strong>QuerySets</strong> and filters, we can ensure that users can only access employee records belonging to their respective departments.</p><p><strong>b. Column-Level Security:</strong></p><p>In the same Employee model, let’s assume we have a “<strong>salary</strong>” field that should only be accessible to authorized HR personnel. By using Django’s Model Field Permissions, we can assign specific read and write permissions to the “<strong>salary</strong>” field, ensuring that only HR personnel can view or modify this sensitive data.</p><p>Finally, implementing the row and column-level security in Django enhances data protection and ensures that sensitive information is only accessible to authorized users. By leveraging Django’s built-in mechanisms, such as custom QuerySets, middleware, and third-party libraries like Django Guardian, developers can enforce fine-grained access control within their applications. Applying row and column-level security measures not only safeguards data but also enhances overall application security, providing peace of mind to both developers and end-users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37fe47b0c563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Designing and Implementing RESTful APIs]]></title>
            <link>https://anilkumarvalluru.medium.com/best-practices-for-designing-and-implementing-restful-apis-4d646fb35056?source=rss-5b2e96c6de9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d646fb35056</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anil Kumar Valluru]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 01:42:44 GMT</pubDate>
            <atom:updated>2023-10-05T01:42:44.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*I2KA4ZSMGCb0JrJmnpLNyw.png" /></figure><p>A RESTful API is an architectural style for designing web services. They provide a simple, standardized way to interact with web resources and can be consumed by a wide range of clients, including web browsers, mobile devices, and other applications. However, building a RESTful API is not as simple as creating a bunch of URLs that return JSON data. In this article, we will discuss some best practices for designing and implementing RESTful APIs, along with examples.</p><h3>1. Use descriptive and consistent resource names</h3><p>One of the key principles of REST is that each resource should have a unique URI. When designing your API, you should identify the resources that you need to expose. For example, if you are building an API for a blog, you might need to expose resources for posts, comments, and users.</p><p>Each resource should have a unique URI. The URI should be consistent with the resource name. For example, if you are building an API for a blog, you might use the following URI to represent a blog post: /api/posts/{post_id}. Using a consistent naming convention will make your API more intuitive and easier to use.</p><h3>2. Use HTTP verbs to indicate resource operations</h3><p>HTTP verbs are used to represent the actions that can be performed on a resource. The most common HTTP verbs are <strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong>, and <strong>DELETE</strong>.</p><ul><li><strong>GET</strong> is used to retrieve a resource.</li><li><strong>POST</strong> is used to create a new resource.</li><li><strong>PUT</strong> is used to update an existing resource.</li><li><strong>DELETE</strong> is used to delete a resource.</li></ul><p>It is important to use the correct HTTP verb for each action. For example, if you want to retrieve a list of users, you would use a GET request. If you want to create a new user, you would use a POST request.</p><h3>3. Use HTTP status codes to indicate response status</h3><p>HTTP status codes are used to indicate the status of a response to an HTTP request. For example, a <strong>200 OK</strong> status code indicates that the request was successful, while a <strong>404 Not Found</strong> status code indicates that the requested resource was not found. Using HTTP status codes in this way makes your API more informative and easier to debug.</p><h3>4. Use versioning to manage API changes</h3><p>As your API evolves, you may need to make changes that are not backward compatible. To manage these changes, it is a good practice to use versioning. For example, you might use the following URI to represent a versioned API endpoint: <strong><em>/api/v1/posts/{post_id}</em></strong>. This will allow you to make changes to the API without breaking existing clients.</p><h3>5. Use caching to improve performance</h3><p>Caching is a technique used to improve the performance of your API by storing frequently accessed data in memory. This can reduce the number of requests to your server and improve response times. For example, you might use the <strong><em>ETag</em></strong> header to implement caching: when a client makes a request for a resource, the server returns an <strong><em>ETag</em></strong> header that represents the resource’s state. If the client makes another request for the same resource, it can include the <strong><em>ETag</em></strong> header in the request, and the server can respond with a 304 Not Modified status code if the resource has not changed.</p><h3>6. Use pagination to limit response size:</h3><p>If your API returns a large number of resources, it is a good practice to use pagination to limit the size of the response. For example, you might use the following URI to represent a paginated API endpoint: <strong><em>/api/posts?page=1&amp;per_page=10</em></strong>. This will allow clients to retrieve a limited subset of the resources and reduce the load on your server.</p><h3>7. Use authentication and authorization:</h3><p>Authentication is the process of verifying the identity of a user. Authorization is the process of granting or denying access to resources based on the user’s identity.</p><p>You should use authentication and authorization to protect your API from unauthorized access.</p><h3>8. Use security best practices:</h3><p>You should use security best practices to protect your API from attack. These best practices include:</p><ul><li>Using strong passwords and security keys.</li><li>Encrypting data in transit and at rest.</li><li>Monitoring your API for suspicious activity.</li></ul><h3>9. Document your API:</h3><p>Documentation is essential for any API. A well-documented API makes it easier for developers to use your API.</p><p>You should document your API using a tool like Swagger. Swagger is a tool that helps you to generate API documentation from your API definition.</p><h3>10. Test your API:</h3><p>You should test your API to ensure that it is working correctly. You can use a tool like Postman to test your API.</p><p><strong>Conclusion:</strong></p><p>These are just a few of the best practices that can be followed when designing and implementing RESTful APIs. Building a RESTful API requires careful consideration of design and implementation decisions. By following these best practices, you can create an API that is easy to use, scalable, and secure.</p><p>#REST #API #RESTAPI #APIDESIGN #WEBDEVELOPMENT #WEBDESIGN #PYTHON #NODEJS #PHP #JAVA</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d646fb35056" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>