<?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 Sintu S@mson on Medium]]></title>
        <description><![CDATA[Stories by Sintu S@mson on Medium]]></description>
        <link>https://medium.com/@sinturana07?source=rss-ec29b600a9ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z1pWH8sVcWHDfyYDhwOnbQ.jpeg</url>
            <title>Stories by Sintu S@mson on Medium</title>
            <link>https://medium.com/@sinturana07?source=rss-ec29b600a9ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:27:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sinturana07/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[How to Use Request Body with Pydantic in FastAPI? | FastAPI Tutorial Series — Chapter 05]]></title>
            <link>https://medium.com/@sinturana07/how-to-use-request-body-with-pydantic-in-fastapi-fastapi-tutorial-series-chapter-05-bd9b94208716?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd9b94208716</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 01:19:14 GMT</pubDate>
            <atom:updated>2026-08-23T01:19:14.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezIpFLafeT1cKoEnTpR8Jw.png" /></figure><h3>Introduction</h3><p>In the previous chapters, we learned about <strong>Path Parameters</strong> and <strong>Query Parameters</strong>.</p><p>But what happens when we need to send a large amount of structured data to an API?</p><p>For example, when creating a new user, we might need:</p><ul><li>Name</li><li>Email</li><li>Age</li><li>Password</li><li>Phone number</li></ul><p>Sending all this information through query parameters is not a good approach.</p><p>Instead, we use a <strong>Request Body</strong>.</p><p>FastAPI uses <strong>Pydantic models</strong> to define, validate, and process request body data.</p><h3>What is a Request Body?</h3><p>A <strong>Request Body</strong> is data sent by the client to the server inside the HTTP request.</p><p>For example, when creating a user, the client can send:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25<br>}</pre><p>This data is called the <strong>Request Body</strong>.</p><p>The server receives this data and processes it.</p><h3>What is Pydantic?</h3><p><strong>Pydantic</strong> is a Python library used for data validation and data parsing.</p><p>FastAPI uses Pydantic models to:</p><ul><li>Define the expected data structure</li><li>Validate incoming data</li><li>Convert data types</li><li>Provide clear validation errors</li><li>Generate API documentation automatically</li></ul><p>For example:</p><pre>from pydantic import BaseModel</pre><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: int</pre><p>This tells FastAPI:</p><blockquote><em>A User must have a name, email, and age.</em></blockquote><h3>Creating Your First Request Body</h3><p>Let’s create a simple FastAPI application.</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>app = FastAPI()<br></pre><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: int<br></pre><pre>@app.post(&quot;/users&quot;)<br>def create_user(user: User):<br>    return {<br>        &quot;name&quot;: user.name,<br>        &quot;email&quot;: user.email,<br>        &quot;age&quot;: user.age<br>    }</pre><h3>Understanding the Code</h3><h3>Step 1: Import FastAPI</h3><pre>from fastapi import FastAPI</pre><p>This allows us to create our FastAPI application.</p><h3>Step 2: Import BaseModel</h3><pre>from pydantic import BaseModel</pre><p>BaseModel is used to create our Pydantic model.</p><h3>Step 3: Create User Model</h3><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: int</pre><p>This defines the structure of the request body.</p><h3>Step 4: Create POST Endpoint</h3><pre>@app.post(&quot;/users&quot;)<br>def create_user(user: User):</pre><p>The user: User tells FastAPI that the request body should follow the User Pydantic model.</p><h3>Sending Request Body</h3><p>Start the server:</p><pre>uvicorn main:app --reload</pre><p>Now send a POST request to:</p><pre>http://127.0.0.1:8000/users</pre><p>Request Body:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25<br>}</pre><p>Response:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25<br>}</pre><h3>Using Swagger UI</h3><p>One of the best features of FastAPI is its automatic API documentation.</p><p>Open:</p><pre>http://127.0.0.1:8000/docs</pre><p>You will see the /users endpoint.</p><p>Click:</p><p><strong>POST → /users → Try it out</strong></p><p>FastAPI automatically generates a request body based on your Pydantic model.</p><p>Example:</p><pre>{<br>    &quot;name&quot;: &quot;string&quot;,<br>    &quot;email&quot;: &quot;string&quot;,<br>    &quot;age&quot;: 0<br>}</pre><p>You can modify the values and click <strong>Execute</strong>.</p><h3>Request Body Validation</h3><p>This is where Pydantic becomes very useful.</p><p>Our model says:</p><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: int</pre><p>If the client sends:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: &quot;twenty five&quot;<br>}</pre><p>FastAPI will reject the request because age should be an integer.</p><p>The response contains a validation error describing the problem.</p><p>We don’t have to manually write validation code.</p><h3>Required Fields</h3><p>By default, fields without default values are required.</p><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: int</pre><p>All three fields are required.</p><p>If the client sends:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;<br>}</pre><p>FastAPI returns a validation error because:</p><pre>email<br>age</pre><p>are missing.</p><h3>Optional Fields</h3><p>We can make a field optional by providing a default value.</p><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: int<br>    phone: str | None = None</pre><p>Now phone is optional.</p><p>This request is valid:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25<br>}</pre><p>And this is also valid:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;phone&quot;: &quot;9876543210&quot;<br>}</pre><h3>Default Values</h3><p>Pydantic models can also have default values.</p><pre>class Product(BaseModel):<br>    name: str<br>    price: float<br>    quantity: int = 1</pre><p>If the client sends:</p><pre>{<br>    &quot;name&quot;: &quot;Keyboard&quot;,<br>    &quot;price&quot;: 999<br>}</pre><p>The value of quantity will automatically be:</p><pre>1</pre><h3>Multiple Data Types</h3><p>A Pydantic model can contain different Python data types.</p><pre>class Product(BaseModel):<br>    name: str<br>    price: float<br>    quantity: int<br>    available: bool</pre><p>Example request:</p><pre>{<br>    &quot;name&quot;: &quot;Keyboard&quot;,<br>    &quot;price&quot;: 999.50,<br>    &quot;quantity&quot;: 10,<br>    &quot;available&quot;: true<br>}</pre><h3>Nested Pydantic Models</h3><p>Pydantic models can also contain other Pydantic models.</p><p>For example:</p><pre>from pydantic import BaseModel<br></pre><pre>class Address(BaseModel):<br>    city: str<br>    state: str<br>    pincode: int<br></pre><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    address: Address</pre><p>Request:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;address&quot;: {<br>        &quot;city&quot;: &quot;Delhi&quot;,<br>        &quot;state&quot;: &quot;Delhi&quot;,<br>        &quot;pincode&quot;: 110001<br>    }<br>}</pre><p>This is called a <strong>nested request body</strong>.</p><h3>List in Request Body</h3><p>We can also send a list of values.</p><pre>class Student(BaseModel):<br>    name: str<br>    subjects: list[str]</pre><p>Request:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;subjects&quot;: [<br>        &quot;Python&quot;,<br>        &quot;FastAPI&quot;,<br>        &quot;Django&quot;<br>    ]<br>}</pre><h3>Request Body + Path Parameter</h3><p>We can use a Request Body together with a Path Parameter.</p><p>Example:</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel</pre><pre>app = FastAPI()<br></pre><pre>class Product(BaseModel):<br>    name: str<br>    price: float<br></pre><pre>@app.put(&quot;/products/{product_id}&quot;)<br>def update_product(product_id: int, product: Product):<br>    return {<br>        &quot;product_id&quot;: product_id,<br>        &quot;product&quot;: product<br>    }</pre><p>Request:</p><pre>PUT /products/101</pre><p>Body:</p><pre>{<br>    &quot;name&quot;: &quot;Keyboard&quot;,<br>    &quot;price&quot;: 999<br>}</pre><p>Response:</p><pre>{<br>    &quot;product_id&quot;: 101,<br>    &quot;product&quot;: {<br>        &quot;name&quot;: &quot;Keyboard&quot;,<br>        &quot;price&quot;: 999<br>    }<br>}</pre><p>Here:</p><ul><li>101 → Path Parameter</li><li>product → Request Body</li></ul><h3>Request Body + Query Parameter</h3><p>We can also combine Request Body with Query Parameters.</p><pre>class Product(BaseModel):<br>    name: str<br>    price: float<br></pre><pre>@app.post(&quot;/products&quot;)<br>def create_product(<br>    product: Product,<br>    notify: bool = False<br>):<br>    return {<br>        &quot;product&quot;: product,<br>        &quot;notify&quot;: notify<br>    }</pre><p>Request:</p><pre>POST /products?notify=true</pre><p>Body:</p><pre>{<br>    &quot;name&quot;: &quot;Mouse&quot;,<br>    &quot;price&quot;: 499<br>}</pre><h3>Adding Validation Rules</h3><p>Pydantic allows us to add validation constraints.</p><p>For example, suppose the age must be between 18 and 100.</p><pre>from pydantic import BaseModel, Field<br></pre><pre>class User(BaseModel):<br>    name: str<br>    age: int = Field(ge=18, le=100)</pre><p>Now:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;age&quot;: 25<br>}</pre><p>is valid.</p><p>But:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;age&quot;: 10<br>}</pre><p>will fail validation.</p><p>Here:</p><ul><li>ge=18 → greater than or equal to 18</li><li>le=100 → less than or equal to 100</li></ul><h3>String Validation</h3><p>We can also define constraints for strings.</p><pre>from pydantic import BaseModel, Field<br></pre><pre>class User(BaseModel):<br>    name: str = Field(min_length=3, max_length=50)</pre><p>This means:</p><pre>Minimum length = 3<br>Maximum length = 50</pre><h3>Email Validation</h3><p>Pydantic can also validate email addresses using EmailStr.</p><pre>from pydantic import BaseModel<br>from pydantic import EmailStr<br></pre><pre>class User(BaseModel):<br>    name: str<br>    email: EmailStr</pre><p>Valid:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;<br>}</pre><p>Invalid:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;hello&quot;<br>}</pre><p>For email validation, install:</p><pre>pip install email-validator</pre><h3>Complete Example</h3><p>Here is a practical example combining several concepts:</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel, Field, EmailStr</pre><pre>app = FastAPI()<br></pre><pre>class User(BaseModel):<br>    name: str = Field(min_length=3, max_length=50)<br>    email: EmailStr<br>    age: int = Field(ge=18, le=100)<br>    phone: str | None = None<br></pre><pre>@app.post(&quot;/users&quot;)<br>def create_user(user: User):<br>    return {<br>        &quot;message&quot;: &quot;User created successfully&quot;,<br>        &quot;user&quot;: user<br>    }</pre><p>Request:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu Kumar&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25,<br>    &quot;phone&quot;: &quot;1234567890&quot;<br>}</pre><p>Response:</p><pre>{<br>    &quot;message&quot;: &quot;User created successfully&quot;,<br>    &quot;user&quot;: {<br>        &quot;name&quot;: &quot;Sintu Kumar&quot;,<br>        &quot;email&quot;: &quot;sintu@example.com&quot;,<br>        &quot;age&quot;: 25,<br>        &quot;phone&quot;: &quot;1234567890&quot;<br>    }<br>}</pre><h3>Why Use Pydantic?</h3><p>Without Pydantic, we might need to manually check:</p><pre>if &quot;name&quot; not in data:<br>    ...</pre><pre>if not isinstance(data[&quot;age&quot;], int):<br>    ...</pre><pre>if data[&quot;age&quot;] &lt; 18:<br>    ...</pre><p>With Pydantic:</p><pre>class User(BaseModel):<br>    name: str<br>    age: int = Field(ge=18)</pre><p>FastAPI handles much of this validation automatically.</p><p>This makes our code:</p><ul><li>Cleaner</li><li>Easier to maintain</li><li>Safer</li><li>More readable</li><li>Easier to document</li></ul><h3>Request Body vs Path vs Query Parameters</h3><p>TypeExamplePurposePath Parameter/users/10Identify a resourceQuery Parameter/users?page=2Filter/customize dataRequest Body{&quot;name&quot;: &quot;Sintu&quot;}Send structured data</p><p>A real-world API might use all three:</p><pre>PUT /users/10?notify=true</pre><p>Request Body:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;<br>}</pre><p>Here:</p><ul><li>10 → Path Parameter</li><li>notify=true → Query Parameter</li><li>JSON object → Request Body</li></ul><h3>Common Mistakes</h3><h3>❌ Forgetting to inherit from BaseModel</h3><p>Incorrect:</p><pre>class User:<br>    name: str<br>    age: int</pre><p>Correct:</p><pre>class User(BaseModel):<br>    name: str<br>    age: int</pre><h3>❌ Sending the wrong JSON structure</h3><p>If the model is:</p><pre>class User(BaseModel):<br>    name: str<br>    age: int</pre><p>Don’t send:</p><pre>{<br>    &quot;username&quot;: &quot;Sintu&quot;<br>}</pre><p>Send:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;age&quot;: 25<br>}</pre><h3>❌ Using Query Parameters for large structured data</h3><p>Avoid:</p><pre>/users?name=Sintu&amp;email=sintu@example.com&amp;age=25</pre><p>For creating or updating resources, a structured Request Body is usually more appropriate:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;,<br>    &quot;age&quot;: 25<br>}</pre><h3>Interview Questions</h3><h3>1. What is a Request Body?</h3><p>A Request Body is data sent by the client to the server as part of an HTTP request, commonly using JSON.</p><h3>2. What is Pydantic?</h3><p>Pydantic is a Python library used for data validation and parsing using Python type hints and models.</p><h3>3. How does FastAPI use Pydantic?</h3><p>FastAPI uses Pydantic models to validate request data, convert compatible types, and generate API documentation.</p><h3>4. How do you create a Pydantic model?</h3><pre>from pydantic import BaseModel</pre><pre>class User(BaseModel):<br>    name: str<br>    age: int</pre><h3>5. Are Request Body fields required?</h3><p>Fields are required by default when they don’t have a default value.</p><h3>6. Can a Request Body contain nested objects?</h3><p>Yes. Pydantic models can contain other Pydantic models.</p><h3>7. Can Request Body be used with Path and Query Parameters?</h3><p>Yes.</p><p>For example:</p><pre>PUT /users/10?notify=true</pre><p>with a JSON Request Body.</p><h3>Easy Trick to Remember</h3><p>Think about an online registration form.</p><p><strong>Path Parameter:</strong></p><blockquote><em>Which user?</em></blockquote><pre>/users/10</pre><p><strong>Query Parameter:</strong></p><blockquote><em>What options do you want?</em></blockquote><pre>/users/10?notify=true</pre><p><strong>Request Body:</strong></p><blockquote><em>What information are you submitting?</em></blockquote><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;,<br>    &quot;email&quot;: &quot;sintu@example.com&quot;<br>}</pre><h3>Memory Trick</h3><blockquote><strong><em>Path = Which resource?</em></strong><em><br></em><strong><em>Query = What options?</em></strong><em><br></em><strong><em>Body = What data?</em></strong></blockquote><h3>Summary</h3><p>In this chapter, we learned:</p><ul><li>What a Request Body is</li><li>What Pydantic is</li><li>How to create Pydantic models</li><li>How to validate incoming JSON data</li><li>Required and optional fields</li><li>Default values</li><li>Nested Pydantic models</li><li>Lists in Request Bodies</li><li>Request Body with Path Parameters</li><li>Request Body with Query Parameters</li><li>Field validation</li><li>Email validation</li><li>Common mistakes</li><li>Request Body vs Path vs Query Parameters</li></ul><p>The combination of <strong>FastAPI + Pydantic</strong> makes it very easy to build APIs that are structured, validated, and well-documented.</p><p><strong>Next Chapter:</strong> <em>Response Model in FastAPI | FastAPI Tutorial Series — Chapter 06</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd9b94208716" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Query Parameters in FastAPI? | FastAPI Tutorial Series — Chapter 04]]></title>
            <link>https://medium.com/@sinturana07/what-are-query-parameters-in-fastapi-fastapi-tutorial-series-chapter-04-fe83c5322930?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe83c5322930</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 12:20:56 GMT</pubDate>
            <atom:updated>2026-07-26T12:21:27.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZqmVufhl6fgr7PERhCFrQ.png" /></figure><h3>Introduction</h3><p>Imagine you&#39;re shopping on Amazon.</p><p>You search for <strong>laptops</strong>, then apply filters like:</p><ul><li>Brand = Dell</li><li>Price &lt; $1000</li><li>Rating = 4★ &amp; above</li></ul><p>The URL becomes something like:</p><pre>https://amazon.com/laptops?brand=Dell&amp;price=1000&amp;rating=4</pre><p>Everything after the <strong>?</strong> is called a <strong>Query Parameter</strong>.</p><p>Query Parameters help us <strong>filter</strong>, <strong>sort</strong>, or <strong>customize</strong> the data returned by an API.</p><h3>What are Query Parameters?</h3><p>A <strong>Query Parameter</strong> is a key-value pair added to the end of a URL after the ? symbol.</p><p>They are generally <strong>optional</strong> and are used to modify or filter the response.</p><p>Example:</p><pre>/users?page=2</pre><p>Here,</p><ul><li>page → Query Parameter name</li><li>2 → Query Parameter value.</li></ul><h3>URL Structure</h3><pre>https://example.com/users?page=2&amp;limit=10</pre><p>Breakdown:</p><p>PartDescription/usersPath?Starts query parameterspage=2Query Parameterlimit=10Another Query Parameter&amp;Separates multiple query parameters</p><h3>Real-Life Example</h3><p>Imagine you&#39;re ordering pizza.</p><p>The pizza shop always knows <strong>which pizza</strong> you ordered.</p><p>But you can customize it:</p><ul><li>Extra Cheese</li><li>Large Size</li><li>Thin Crust</li></ul><p>These customizations are like <strong>Query Parameters</strong>.</p><p>Example API:</p><pre>/pizza?size=large&amp;cheese=true</pre><h3>Basic Query Parameter Example</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/users&quot;)<br>def get_users(page: int = 1):<br>    return {&quot;page&quot;: page}</pre><p>Run:</p><pre>uvicorn main:app --reload</pre><p>Request:</p><pre>/users?page=2</pre><p>Response:</p><pre>{<br>    &quot;page&quot;: 2<br>}</pre><h3>Default Values</h3><p>If the user doesn&#39;t provide the query parameter, FastAPI uses the default value.</p><pre>@app.get(&quot;/products&quot;)<br>def get_products(page: int = 1):<br>    return {&quot;page&quot;: page}</pre><p>Request:</p><pre>/products</pre><p>Response:</p><pre>{<br>    &quot;page&quot;: 1<br>}</pre><h3>Multiple Query Parameters</h3><pre>@app.get(&quot;/products&quot;)<br>def get_products(page: int = 1, limit: int = 10):<br>    return {<br>        &quot;page&quot;: page,<br>        &quot;limit&quot;: limit<br>    }</pre><p>Request:</p><pre>/products?page=3&amp;limit=20</pre><p>Response:</p><pre>{<br>    &quot;page&quot;: 3,<br>    &quot;limit&quot;: 20<br>}</pre><h3>Optional Query Parameters</h3><pre>from typing import Optional<br><br>@app.get(&quot;/search&quot;)<br>def search(keyword: Optional[str] = None):<br>    return {&quot;keyword&quot;: keyword}</pre><p>Request:</p><pre>/search</pre><p>Response:</p><pre>{<br>    &quot;keyword&quot;: null<br>}</pre><p>Request:</p><pre>/search?keyword=fastapi</pre><p>Response:</p><pre>{<br>    &quot;keyword&quot;: &quot;fastapi&quot;<br>}</pre><h3>Boolean Query Parameters</h3><pre>@app.get(&quot;/items&quot;)<br>def get_items(active: bool = False):<br>    return {&quot;active&quot;: active}</pre><p>Request:</p><pre>/items?active=true</pre><p>Response:</p><pre>{<br>    &quot;active&quot;: true<br>}</pre><p>FastAPI accepts values like:</p><ul><li>true</li><li>false</li><li>1</li><li>0</li><li>yes</li><li>no</li><li>on</li><li>off</li></ul><h3>String Query Parameters</h3><pre>@app.get(&quot;/students&quot;)<br>def get_student(name: str = &quot;&quot;):<br>    return {&quot;name&quot;: name}</pre><p>Request:</p><pre>/students?name=Sintu</pre><p>Response:</p><pre>{<br>    &quot;name&quot;: &quot;Sintu&quot;<br>}</pre><h3>Float Query Parameters</h3><pre>@app.get(&quot;/products&quot;)<br>def get_products(price: float = 0):<br>    return {&quot;price&quot;: price}</pre><p>Request:</p><pre>/products?price=99.99</pre><p>Response:</p><pre>{<br>    &quot;price&quot;: 99.99<br>}</pre><h3>Required Query Parameters</h3><p>A query parameter becomes <strong>required</strong> if no default value is provided.</p><pre>@app.get(&quot;/login&quot;)<br>def login(username: str):<br>    return {&quot;username&quot;: username}</pre><p>Request:</p><pre>/login</pre><p>Response:</p><pre>{<br>  &quot;detail&quot;: [<br>    {<br>      &quot;type&quot;: &quot;missing&quot;,<br>      &quot;loc&quot;: [<br>        &quot;query&quot;,<br>        &quot;username&quot;<br>      ],<br>      &quot;msg&quot;: &quot;Field required&quot;<br>    }<br>  ]<br>}</pre><p>Valid request:</p><pre>/login?username=Sintu</pre><h3>Combining Path and Query Parameters</h3><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int, details: bool = False):<br>    return {<br>        &quot;user_id&quot;: user_id,<br>        &quot;details&quot;: details<br>    }</pre><p>Request:</p><pre>/users/10?details=true</pre><p>Response:</p><pre>{<br>    &quot;user_id&quot;: 10,<br>    &quot;details&quot;: true<br>}</pre><h3>Filtering Data Example</h3><pre>@app.get(&quot;/products&quot;)<br>def get_products(category: str = &quot;&quot;, price: float = 0):<br>    return {<br>        &quot;category&quot;: category,<br>        &quot;price&quot;: price<br>    }</pre><p>Request:</p><pre>/products?category=electronics&amp;price=500</pre><p>Response:</p><pre>{<br>    &quot;category&quot;: &quot;electronics&quot;,<br>    &quot;price&quot;: 500<br>}</pre><h3>Pagination Example</h3><pre>@app.get(&quot;/users&quot;)<br>def get_users(page: int = 1, limit: int = 10):<br>    return {<br>        &quot;page&quot;: page,<br>        &quot;limit&quot;: limit<br>    }</pre><p>Request:</p><pre>/users?page=5&amp;limit=20</pre><p>Response:</p><pre>{<br>    &quot;page&quot;: 5,<br>    &quot;limit&quot;: 20<br>}</pre><h3>Search Example</h3><pre>@app.get(&quot;/search&quot;)<br>def search(keyword: str = &quot;&quot;, sort: str = &quot;asc&quot;):<br>    return {<br>        &quot;keyword&quot;: keyword,<br>        &quot;sort&quot;: sort<br>    }</pre><p>Request:</p><pre>/search?keyword=python&amp;sort=desc</pre><p>Response:</p><pre>{<br>    &quot;keyword&quot;: &quot;python&quot;,<br>    &quot;sort&quot;: &quot;desc&quot;<br>}</pre><h3>Path Parameter vs Query Parameter</h3><p>Path ParameterQuery ParameterPart of URL pathComes after ?RequiredUsually optionalIdentifies a resourceFilters or customizes the responseExample: /users/10Example: /users?page=2</p><h3>Common Mistakes</h3><h3>Forgetting the ?</h3><p>Incorrect:</p><pre>/users/page=2</pre><p>Correct:</p><pre>/users?page=2</pre><h3>Using Multiple ?</h3><p>Incorrect:</p><pre>/users?page=2?limit=10</pre><p>Correct:</p><pre>/users?page=2&amp;limit=10</pre><h3>Wrong Data Type</h3><pre>@app.get(&quot;/users&quot;)<br>def get_users(page: int = 1):<br>    return {&quot;page&quot;: page}</pre><p>Request:</p><pre>/users?page=abc</pre><p>Response:</p><pre>{<br>  &quot;detail&quot;: [<br>    {<br>      &quot;type&quot;: &quot;int_parsing&quot;,<br>      &quot;msg&quot;: &quot;Input should be a valid integer&quot;<br>    }<br>  ]<br>}</pre><p>FastAPI automatically validates the input.</p><h3>Real API Examples</h3><h3>Get Users (Pagination)</h3><pre>GET /users?page=2&amp;limit=20</pre><h3>Search Products</h3><pre>GET /products?category=laptop&amp;price=1000</pre><h3>Search Blogs</h3><pre>GET /blogs?author=John</pre><h3>Filter Orders</h3><pre>GET /orders?status=completed</pre><h3>Download Videos</h3><pre>GET /videos?quality=1080p</pre><h3>Interview Questions</h3><h3>1. What is a Query Parameter?</h3><p>A Query Parameter is a key-value pair added after the ? in a URL to filter, sort, or customize the response.</p><h3>2. Are Query Parameters required?</h3><p>Not always. They are optional when a default value is provided. If no default value is given, they become required.</p><h3>3. Can there be multiple Query Parameters?</h3><p>Yes.</p><p>Example:</p><pre>/products?page=2&amp;limit=10</pre><h3>4. What symbol starts Query Parameters?</h3><p>The ? symbol.</p><h3>5. What symbol separates multiple Query Parameters?</h3><p>The &amp; symbol.</p><h3>6. Does FastAPI validate Query Parameters?</h3><p>Yes. FastAPI automatically validates and converts query parameters to the specified type.</p><h3>7. When should you use Query Parameters?</h3><p>Use Query Parameters for:</p><ul><li>Searching</li><li>Filtering</li><li>Pagination</li><li>Sorting</li><li>Optional settings</li></ul><h3>Easy Trick to Remember (Interview)</h3><p>Think about ordering food online:</p><ul><li><strong>Restaurant ID</strong> → Path Parameter (Which restaurant?)</li><li><strong>Extra Cheese, Size, Spicy</strong> → Query Parameters (How do you want it?)</li></ul><p>Example:</p><pre>/orders/25?size=large&amp;spicy=true</pre><ul><li>25 → Path Parameter</li><li>size=large → Query Parameter</li><li>spicy=true → Query Parameter</li></ul><p><strong>Memory Trick:</strong></p><blockquote><strong><em>Path = &quot;Which resource?&quot;</em></strong><em><br> </em><strong><em>Query = &quot;How do you want it?&quot;</em></strong></blockquote><h3>Path + Query Together</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/products/{product_id}&quot;)<br>def get_product(<br>    product_id: int,<br>    review: bool = False,<br>    lang: str = &quot;en&quot;<br>):<br>    return {<br>        &quot;product_id&quot;: product_id,<br>        &quot;review&quot;: review,<br>        &quot;language&quot;: lang<br>    }</pre><p>Request:</p><pre>/products/101?review=true&amp;lang=en</pre><p>Response:</p><pre>{<br>    &quot;product_id&quot;: 101,<br>    &quot;review&quot;: true,<br>    &quot;language&quot;: &quot;en&quot;<br>}</pre><h3>Summary</h3><ul><li>Query Parameters appear after the ? in a URL.</li><li>They are used for filtering, searching, sorting, pagination, and optional settings.</li><li>Multiple query parameters are separated by &amp;.</li><li>FastAPI automatically validates and converts query parameter types.</li><li>Query Parameters are usually optional, but they become required if no default value is provided.</li><li>Path Parameters identify <strong>which resource</strong>, while Query Parameters specify <strong>how the data should be returned</strong>.</li></ul><p><strong>Next Chapter:</strong> <em>Request Body in FastAPI | FastAPI Tutorial Series – Chapter 05</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe83c5322930" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Path Parameters in FastAPI? | FastAPI Tutorial Series — Chapter 03]]></title>
            <link>https://medium.com/@sinturana07/what-are-path-parameters-in-fastapi-fastapi-tutorial-series-chapter-03-f9d9377b5883?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d9377b5883</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[path-parameter]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 07:07:15 GMT</pubDate>
            <atom:updated>2026-07-26T07:07:15.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5I0lfUPXKSIlWULZNBo3tA.png" /></figure><h3>Introduction</h3><p>Imagine you are visiting a website like Amazon:</p><pre>https://amazon.com/product/101</pre><p>or Instagram:</p><pre>https://instagram.com/user/virat.kohli</pre><p>Notice the values <strong>101</strong> and <strong>virat.kohli</strong>?</p><p>These values are part of the URL and change depending on what data you want. These are called <strong>Path Parameters</strong>.</p><p>FastAPI makes it extremely easy to capture these values.</p><h3>What are Path Parameters?</h3><p>A <strong>Path Parameter</strong> is a variable inside the URL path that is used to identify a specific resource.</p><p>Instead of writing separate APIs for every user or product, we write one API and pass the value in the URL.</p><p>For example:</p><pre>/users/1<br>/users/2<br>/users/3</pre><p>Here,</p><pre>1<br>2<br>3</pre><p>are Path Parameters.</p><h3>Real-Life Example</h3><p>Suppose you work in a company.</p><p>Your employee ID is:</p><pre>EMP101</pre><p>Your friend’s ID is:</p><pre>EMP102</pre><p>Instead of creating APIs like:</p><pre>/employee1<br>/employee2<br>/employee3</pre><p>we create one API:</p><pre>/employee/{employee_id}</pre><p>Then,</p><pre>/employee/101</pre><p>returns Employee 101.</p><pre>/employee/102</pre><p>returns Employee 102.</p><p>Simple and reusable.</p><h3>Syntax in FastAPI</h3><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id):<br>    return {&quot;user_id&quot;: user_id}</pre><p>Run the server:</p><pre>uvicorn main:app --reload</pre><p>Open:</p><pre>http://127.0.0.1:8000/users/10</pre><p>Output</p><pre>{<br>    &quot;user_id&quot;: &quot;10&quot;<br>}</pre><h3>Path Parameters with Type Conversion</h3><p>FastAPI automatically converts values.</p><p>Example:</p><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    return {&quot;user_id&quot;: user_id}</pre><p>Request:</p><pre>/users/25</pre><p>Response</p><pre>{<br>    &quot;user_id&quot;: 25<br>}</pre><p>Notice:</p><p>The value becomes an <strong>integer</strong>, not a string.</p><h3>What if the Wrong Type is Passed?</h3><p>API:</p><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    return {&quot;user_id&quot;: user_id}</pre><p>Request:</p><pre>/users/abc</pre><p>FastAPI Response:</p><pre>{<br>  &quot;detail&quot;: [<br>    {<br>      &quot;type&quot;: &quot;int_parsing&quot;,<br>      &quot;loc&quot;: [<br>        &quot;path&quot;,<br>        &quot;user_id&quot;<br>      ],<br>      &quot;msg&quot;: &quot;Input should be a valid integer&quot;<br>    }<br>  ]<br>}</pre><p>No extra validation code is required.</p><p>FastAPI does it automatically.</p><h3>Multiple Path Parameters</h3><p>Example:</p><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/users/{user_id}/orders/{order_id}&quot;)<br>def get_order(user_id: int, order_id: int):<br>    return {<br>        &quot;user_id&quot;: user_id,<br>        &quot;order_id&quot;: order_id<br>    }</pre><p>Request:</p><pre>/users/5/orders/101</pre><p>Response:</p><pre>{<br>    &quot;user_id&quot;: 5,<br>    &quot;order_id&quot;: 101<br>}</pre><h3>String Path Parameters</h3><pre>@app.get(&quot;/students/{name}&quot;)<br>def get_student(name: str):<br>    return {&quot;student&quot;: name}</pre><p>Request:</p><pre>/students/Sintu</pre><p>Response:</p><pre>{<br>    &quot;student&quot;: &quot;Sintu&quot;<br>}</pre><h3>Float Path Parameters</h3><pre>@app.get(&quot;/price/{amount}&quot;)<br>def get_price(amount: float):<br>    return {&quot;amount&quot;: amount}</pre><p>Request:</p><pre>/price/299.99</pre><p>Response:</p><pre>{<br>    &quot;amount&quot;: 299.99<br>}</pre><h3>Boolean Path Parameters</h3><pre>@app.get(&quot;/status/{active}&quot;)<br>def get_status(active: bool):<br>    return {&quot;active&quot;: active}</pre><p>Request:</p><pre>/status/true</pre><p>Response:</p><pre>{<br>    &quot;active&quot;: true<br>}</pre><h3>Order of Routes Matters</h3><p>❌ Incorrect:</p><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: str):<br>    return {&quot;user&quot;: user_id}</pre><pre>@app.get(&quot;/users/me&quot;)<br>def get_me():<br>    return {&quot;user&quot;: &quot;Current User&quot;}</pre><p>Request:</p><pre>/users/me</pre><p>Output:</p><pre>{<br>    &quot;user&quot;: &quot;me&quot;<br>}</pre><p>Because &quot;me&quot; is treated as the user_id.</p><p>Correct:</p><pre>@app.get(&quot;/users/me&quot;)<br>def get_me():<br>    return {&quot;user&quot;: &quot;Current User&quot;}</pre><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: str):<br>    return {&quot;user&quot;: user_id}</pre><p>Now,</p><pre>/users/me</pre><p>returns:</p><pre>{<br>    &quot;user&quot;: &quot;Current User&quot;<br>}</pre><h3>Path Parameters with Enum</h3><p>Enums restrict users to predefined values.</p><pre>from enum import Enum<br>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre>class ModelName(str, Enum):<br>    laptop = &quot;laptop&quot;<br>    mobile = &quot;mobile&quot;<br>    tablet = &quot;tablet&quot;</pre><pre>@app.get(&quot;/products/{model}&quot;)<br>def get_product(model: ModelName):<br>    return {&quot;model&quot;: model}</pre><p>Valid URLs:</p><pre>/products/laptop<br>/products/mobile<br>/products/tablet</pre><p>Invalid:</p><pre>/products/watch</pre><p>FastAPI returns a validation error.</p><h3>Path vs Query Parameters</h3><p>Path ParameterQuery ParameterPart of the URL pathComes after ?RequiredUsually optionalIdentifies a specific resourceFilters or modifies results</p><p>Example:</p><p>Path Parameter</p><pre>/users/10</pre><p>Query Parameter</p><pre>/users?page=2</pre><p>Combined</p><pre>/users/10?details=true</pre><p>10 → Path Parameter</p><p>details=true → Query Parameter</p><h3>Real API Examples</h3><h3>Get User</h3><pre>GET /users/15</pre><p>Returns user with ID <strong>15</strong>.</p><h3>Get Product</h3><pre>GET /products/101</pre><p>Returns product <strong>101</strong>.</p><h3>Get Order</h3><pre>GET /orders/500</pre><p>Returns order <strong>500</strong>.</p><h3>Instagram Profile</h3><pre>GET /profile/virat.kohli</pre><p>Returns the profile of <strong>virat.kohli</strong>.</p><h3>Common Mistakes</h3><p>❌ Forgetting curly braces</p><pre>@app.get(&quot;/users/user_id&quot;)</pre><p>Correct:</p><pre>@app.get(&quot;/users/{user_id}&quot;)</pre><p>❌ Using the wrong type</p><pre>user_id: int</pre><p>Request:</p><pre>/users/abc</pre><p>Results in a validation error because &quot;abc&quot; is not an integer.</p><p>❌ Defining dynamic routes before static routes</p><p>Always place static routes like /users/me before dynamic routes like /users/{user_id}.</p><h3>Interview Questions</h3><h3>1. What is a Path Parameter?</h3><p>A Path Parameter is a variable embedded in the URL path that identifies a specific resource.</p><h3>2. Are Path Parameters required?</h3><p>Yes. A request must include them for the route to match.</p><h3>3. Does FastAPI validate Path Parameters?</h3><p>Yes. It validates and converts them automatically based on the declared type.</p><h3>4. Can there be multiple Path Parameters?</h3><p>Yes.</p><p>Example:</p><pre>/users/10/orders/200</pre><h3>5. What is the difference between Path and Query Parameters?</h3><ul><li><strong>Path Parameters</strong> identify a resource (for example, /users/10).</li><li><strong>Query Parameters</strong> filter or modify the request (for example, /users?page=2).</li></ul><h3>Easy Trick to Remember (Interview)</h3><p>Think of a <strong>house address</strong>:</p><ul><li><strong>House Number</strong> → Path Parameter (identifies the exact house)</li><li><strong>Room Preference</strong> → Query Parameter (adds extra details)</li></ul><p>Example:</p><pre>House Address:<br>House No. 25</pre><p>Equivalent API:</p><pre>/users/25</pre><p>Filtering details:</p><pre>/users/25?details=true</pre><p><strong>Memory trick:</strong></p><blockquote><strong><em>Path = “Which resource?”</em></strong><em><br> </em><strong><em>Query = “How do you want it?”</em></strong></blockquote><h3>Summary</h3><ul><li>Path Parameters are variables inside the URL path.</li><li>They uniquely identify a resource.</li><li>FastAPI automatically validates and converts data types.</li><li>Multiple Path Parameters are supported.</li><li>Static routes should be declared before dynamic routes.</li><li>Use Path Parameters for identifying resources and Query Parameters for filtering or additional options.</li></ul><p><strong>Next Chapter:</strong> <em>Query Parameters in FastAPI | FastAPI Tutorial Series — Chapter 04</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d9377b5883" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Your First API in FastAPI? | FastAPI Tutorial Series — Chapter 02]]></title>
            <link>https://medium.com/@sinturana07/how-to-create-your-first-api-in-fastapi-fastapi-tutorial-series-chapter-02-96321c085ab2?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/96321c085ab2</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-07-21T13:52:25.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EoLacsIszmdhB2YMt9trg.png" /></figure><h3>1. Introduction</h3><ul><li>What you will build</li><li>Why FastAPI is beginner-friendly</li><li>What readers will learn in this chapter</li></ul><p>Example:</p><blockquote><em>In this chapter, we’ll build our first FastAPI application from scratch. By the end of this tutorial, you’ll know how to install FastAPI, create your first API, run the development server, and test the API using Swagger UI.</em></blockquote><h3>2. Prerequisites</h3><p>Mention what users should have installed.</p><ul><li>Python 3.10+</li><li>VS Code or PyCharm</li><li>pip</li><li>Terminal</li></ul><h3>3. Create a Project Folder</h3><pre>mkdir fastapi-tutorial<br>cd fastapi-tutorial</pre><p>Explain why we create a dedicated project folder.</p><h3>4. Create a Virtual Environment</h3><p>Windows</p><pre>python -m venv venv</pre><p>Linux/macOS</p><pre>python3 -m venv venv</pre><p>Explain:</p><ul><li>Why virtual environments are important</li><li>They isolate project dependencies</li></ul><h3>5. Activate Virtual Environment</h3><p>Windows</p><pre>venv\Scripts\activate</pre><p>Linux/macOS</p><pre>source venv/bin/activate</pre><p>Show what the terminal looks like after activation.</p><h3>6. Install FastAPI</h3><pre>pip install fastapi</pre><p>Explain what FastAPI is.</p><h3>7. Install Uvicorn</h3><pre>pip install uvicorn</pre><p>Explain:</p><ul><li>FastAPI is the framework.</li><li>Uvicorn is the ASGI server that runs the application.</li></ul><h3>8. Verify Installation</h3><pre>pip list</pre><p>Readers should see:</p><ul><li>fastapi</li><li>uvicorn</li></ul><h3>9. Create main.py</h3><p>Project structure:</p><pre>fastapi-tutorial/<br>│── venv/<br>│── main.py</pre><p>Explain why main.py is commonly used as the entry point.</p><h3>10. Write Your First FastAPI Code</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def home():<br>    return {&quot;message&quot;: &quot;Welcome to FastAPI&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QblDtJte6eC6VDtDi0tPpg.png" /></figure><p>Explain every line:</p><ul><li>import FastAPI</li><li>create app</li><li>decorator</li><li>route</li><li>return JSON</li></ul><h3>11. Run the Server</h3><pre>uvicorn main:app --reload</pre><p>Explain:</p><ul><li>main</li><li>app</li><li>--reload</li></ul><h3>12. Open in Browser</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6DogGhxsFSEA6_KH_KpOA.png" /></figure><p>Visit:</p><p><a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a></p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*O-LkItBBX1T5wHd8yGxywQ.png" /></figure><h3>13. Swagger Documentation</h3><p>Visit:</p><pre>http://127.0.0.1:8000/docs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPjZtPp9j1AC4dMyCEJIGg.png" /></figure><p>Explain:</p><ul><li>Automatic API documentation</li><li>Interactive testing</li><li>No Postman required for simple APIs</li></ul><h3>14. ReDoc Documentation</h3><p>Visit:</p><pre>http://127.0.0.1:8000/redoc</pre><p>Explain the difference between Swagger UI and ReDoc.</p><h3>15. How FastAPI Works</h3><p>Simple flow diagram:</p><pre>Browser<br><br>      ↓<br><br>HTTP Request<br><br>      ↓<br><br>Uvicorn Server<br><br>      ↓<br><br>FastAPI<br><br>      ↓<br><br>Route Function<br><br>      ↓<br><br>JSON Response<br><br>      ↓<br><br>Browser</pre><h3>16. Common Errors</h3><p>Examples:</p><h3>Module not found</h3><p><em>ModuleNotFoundError</em></p><p>Solution:</p><pre>pip install fastapi</pre><p><strong>Uvicorn not found</strong></p><p><em>uvicorn: command not found</em></p><p>Solution:</p><pre>pip install uvicorn</pre><p>Address already in use</p><pre>Port 8000 already in use</pre><p>Solution:</p><p>Use another port:</p><pre>uvicorn main:app --reload --port 8001</pre><h3>17. Summary</h3><p>Recap what readers learned:</p><ul><li>Installed FastAPI</li><li>Installed Uvicorn</li><li>Created a project</li><li>Wrote the first API</li><li>Ran the server</li><li>Tested the API</li><li>Used Swagger UI</li><li>Used ReDoc</li></ul><h3>18. What’s Next?</h3><p>End the article with a preview:</p><blockquote><em>In </em><strong><em>Chapter 03</em></strong><em>, we’ll learn </em><strong><em>Path Parameters in FastAPI</em></strong><em> and build dynamic APIs that accept values directly from the URL.</em></blockquote><p>This structure is beginner-friendly, covers all essential concepts, and is ideal for a Medium tutorial series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96321c085ab2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Concurrency and async/await in FastAPI? | FastAPI Tutorial Series – Chapter 01]]></title>
            <link>https://medium.com/@sinturana07/what-is-concurrency-and-async-await-in-fastapi-fastapi-tutorial-series-chapter-01-bb67defd5c89?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb67defd5c89</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 06:46:03 GMT</pubDate>
            <atom:updated>2026-07-19T06:46:03.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPUovYYZGWhwGbg3TWWNRg.png" /></figure><h3>Why Should We Learn This First?</h3><p>Before learning FastAPI, you need to understand <strong>Concurrency</strong> and <strong>async/</strong><strong>await</strong> because <strong>FastAPI is built around asynchronous programming</strong>.</p><p>One of the biggest reasons FastAPI is so fast is that it can handle many requests efficiently without making users wait unnecessarily.</p><p>Think of it this way:</p><ul><li>A traditional web framework often processes one request while waiting for operations like database queries or API calls to finish.</li><li>FastAPI uses <strong>asynchronous programming</strong>, allowing it to handle other requests while one request is waiting.</li></ul><p>This is why FastAPI performs so well under high traffic.</p><h3>What is Concurrency?</h3><p>Concurrency means <strong>handling multiple tasks efficiently by switching between them whenever one task is waiting</strong>.</p><p>It does <strong>not</strong> mean everything runs at the exact same time.</p><h3>Real-Life Example</h3><p>Imagine you are cooking dinner.</p><p>You put rice on the stove. It takes 20 minutes to cook.</p><h3>Without Concurrency</h3><p>You sit and wait for 20 minutes.</p><p>After that, you start cutting vegetables.</p><p>After that, you start making chapati.</p><p>Total time becomes much longer.</p><h3>With Concurrency</h3><p>You put rice on the stove.</p><p>While the rice is cooking, you:</p><ul><li>Cut vegetables</li><li>Prepare curry</li><li>Make chapati</li></ul><p>By the time the rice is ready, almost everything else is also ready.</p><p>You didn’t do two things at exactly the same moment — you simply didn’t waste time while waiting.</p><p>This is concurrency.</p><h3>What is Asynchronous Programming?</h3><p>Asynchronous programming allows a program to continue doing useful work while waiting for another task to finish.</p><p>Examples of waiting:</p><ul><li>Database query</li><li>API request</li><li>File upload</li><li>File download</li><li>Sending an email</li><li>Reading a file</li></ul><p>Instead of stopping the program during these waiting periods, asynchronous programming lets it handle other tasks.</p><h3>What is async?</h3><p>The async keyword defines a function that can perform asynchronous operations.</p><p>Example:</p><pre>async def get_user():<br>    print(&quot;Getting user...&quot;)</pre><p>The async keyword tells Python:</p><blockquote><em>“This function may need to wait for some operation.”</em></blockquote><h3>What is await?</h3><p>The await keyword is used inside an async function.</p><p>It means:</p><blockquote><em>“Pause this function until this operation finishes, but let other asynchronous tasks continue running.”</em></blockquote><p>Example:</p><pre>user = await database.fetch_one(query)</pre><p>Here, the function waits for the database response.</p><p>During this waiting time, FastAPI can process other incoming requests.</p><h3>Visual Example</h3><p>Without async</p><pre>Request 1<br>   ↓<br>Database Waiting<br>   ↓<br>Response</pre><pre>Request 2 starts only after Request 1 finishes.</pre><p>With async</p><pre>Request 1<br>      ↓<br>Waiting for Database</pre><pre>↘</pre><pre>Request 2 starts immediately</pre><pre>↘</pre><pre>Request 3 starts immediately</pre><pre>↘</pre><pre>Database returns data</pre><pre>Request 1 completes</pre><p>This is why FastAPI can efficiently handle thousands of users.</p><h3>Understanding await with an Example</h3><p>Suppose downloading a file takes 5 seconds.</p><p>Normal code:</p><pre>download_file()<br>print(&quot;Completed&quot;)</pre><p>The program waits for the download before moving on.</p><p>Using await:</p><pre>await download_file()<br>print(&quot;Completed&quot;)</pre><p>While waiting for the download, other asynchronous tasks can continue executing.</p><h3>Normal Function vs Async Function</h3><h3>Normal Function</h3><pre>def hello():<br>    return &quot;Hello&quot;</pre><p>Runs from start to finish without pausing.</p><h3>Async Function</h3><pre>async def hello():<br>    return &quot;Hello&quot;</pre><p>Can pause when it encounters an await and resume later.</p><h3>Simple Async Example</h3><pre>import asyncio<br><br>async def task():<br>    print(&quot;Task Started&quot;)<br><br>    await asyncio.sleep(3)<br><br>    print(&quot;Task Finished&quot;)<br><br>asyncio.run(task())</pre><p>Output:</p><pre>Task Started</pre><pre>(wait 3 seconds)</pre><pre>Task Finished</pre><p>The important part is that during those 3 seconds, other asynchronous tasks could run.</p><h3>Multiple Tasks Example</h3><pre>import asyncio<br><br>async def task1():<br>    print(&quot;Task 1 Started&quot;)<br>    await asyncio.sleep(3)<br>    print(&quot;Task 1 Finished&quot;)<br><br>async def task2():<br>    print(&quot;Task 2 Started&quot;)<br>    await asyncio.sleep(2)<br>    print(&quot;Task 2 Finished&quot;)<br><br>async def main():<br>    await asyncio.gather(<br>        task1(),<br>        task2()<br>    )<br><br>asyncio.run(main())async def task1():<br>    print(&quot;Task 1 Started&quot;)<br>    await asyncio.sleep(3)<br>    print(&quot;Task 1 Finished&quot;)</pre><p>Output:</p><pre>Task 1 Started<br>Task 2 Started<br>Task 2 Finished<br>Task 1 Finished</pre><p>Both tasks start immediately, and while one is waiting, the other can make progress.</p><h3>Where FastAPI Uses async</h3><p>FastAPI commonly uses async for operations that involve waiting:</p><ul><li>Database queries</li><li>Calling external APIs</li><li>Uploading files</li><li>Downloading files</li><li>Sending emails</li><li>Cloud storage operations</li><li>Redis access</li><li>Authentication services</li></ul><p>Example:</p><pre>@app.get(&quot;/users/{id}&quot;)<br>async def get_user(id: int):<br>    user = await database.fetch_one(<br>        &quot;SELECT * FROM users WHERE id = :id&quot;,<br>        {&quot;id&quot;: id}<br>    )<br>    return user</pre><p>While waiting for the database, FastAPI can process other requests.</p><h3>When Should You Use async?</h3><p>Use async when your code waits for I/O operations such as:</p><ul><li>Database operations</li><li>HTTP API calls</li><li>Reading or writing files</li><li>Cloud services</li><li>Message queues</li><li>Email services</li></ul><h3>When Should You NOT Use async?</h3><p>Avoid async for CPU-intensive tasks such as:</p><ul><li>Image processing</li><li>Video encoding</li><li>Machine learning training</li><li>Large mathematical computations</li><li>Heavy data processing</li></ul><p>These tasks keep the CPU busy instead of waiting.</p><h3>Key Takeaways</h3><ul><li><strong>Concurrency</strong> means handling multiple tasks efficiently by switching between them while they wait.</li><li><strong>async</strong> declares a function that can pause during waiting operations.</li><li><strong>await</strong> pauses only the current async function and allows other async tasks to continue.</li><li>FastAPI’s excellent performance comes from using asynchronous programming for I/O-bound operations.</li><li>Understanding concurrency and async/await is essential before learning FastAPI routing, dependency injection, databases, or background tasks.</li></ul><p>This chapter gives learners the mental model they need before writing their first FastAPI application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb67defd5c89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Official Tutorials Every Python Backend Developer Should Follow#Chapter-33]]></title>
            <link>https://medium.com/@sinturana07/official-tutorials-every-python-backend-developer-should-follow-chapter-33-0c065cc9e76c?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c065cc9e76c</guid>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 05:01:02 GMT</pubDate>
            <atom:updated>2026-02-03T05:01:02.148Z</atom:updated>
            <content:encoded><![CDATA[<h3>Official Tutorials Every Python Backend Developer Should Follow</h3><p>When learning backend development, <strong>official documentation</strong> is the most reliable source.<br> It is always <strong>up to date</strong>, <strong>accurate</strong>, and written by the <strong>creators of the technology</strong>.</p><p>Below is a curated list of <strong>official tutorials</strong> that every Python backend developer should bookmark and follow.</p><h3>Python — Official Tutorial</h3><p>Python is the <strong>foundation</strong> of backend development.</p><p>The official Python tutorial covers:</p><ul><li>Basic syntax and data types</li><li>Control flow and functions</li><li>Modules and packages</li><li>File handling and exceptions</li></ul><p>This tutorial is ideal for:</p><ul><li>Beginners starting with Python</li><li>Developers revising core Python concepts</li></ul><p>👉 Official link:<br> <a href="https://docs.python.org/3/tutorial/index.html">https://docs.python.org/3/tutorial/index.html</a></p><h3>Django — Official Documentation</h3><p>Django is a <strong>full-stack web framework</strong> used to build large and scalable applications.</p><p>The Django documentation explains:</p><ul><li>Project and app structure</li><li>Models, views, and templates</li><li>Django ORM</li><li>Authentication and admin panel</li></ul><p>It is best suited for:</p><ul><li>Building complete web applications</li><li>Enterprise-level projects</li></ul><p>👉 Official link:<br> <a href="https://docs.djangoproject.com/en/6.0/">https://docs.djangoproject.com/en/6.0/</a></p><h3>FastAPI — Official Tutorial</h3><p>FastAPI is a <strong>modern framework</strong> for building <strong>high-performance APIs</strong>.</p><p>The FastAPI tutorial includes:</p><ul><li>API creation using Python type hints</li><li>Async programming</li><li>Request validation</li><li>Automatic Swagger documentation</li></ul><p>It is widely used for:</p><ul><li>Microservices</li><li>REST APIs</li><li>Machine learning backends</li></ul><p>👉 Official link:<br> <a href="https://fastapi.tiangolo.com/tutorial/">https://fastapi.tiangolo.com/tutorial/</a></p><h3>Flask — Official Documentation</h3><p>Flask is a <strong>lightweight microframework</strong> that gives developers full flexibility.</p><p>The Flask documentation covers:</p><ul><li>Routing and request handling</li><li>Templates using Jinja</li><li>Blueprints for project structure</li><li>Extensions for added features</li></ul><p>Flask is ideal for:</p><ul><li>Small web applications</li><li>Lightweight APIs</li><li>Learning web development fundamentals</li></ul><p>👉 Official link:<br> <a href="https://flask.palletsprojects.com/en/stable/">https://flask.palletsprojects.com/en/stable/</a></p><h3>Docker — Official Getting Started Guide</h3><p>Docker is used to <strong>containerize applications</strong>, making them portable and consistent across environments.</p><p>The Docker tutorial explains:</p><ul><li>Images and containers</li><li>Dockerfiles</li><li>Volumes and networks</li><li>Running applications in containers</li></ul><p>Docker is essential for:</p><ul><li>Deployment</li><li>DevOps workflows</li><li>Microservices architecture</li></ul><p>👉 Official link:<br> <a href="https://docs.docker.com/get-started/">https://docs.docker.com/get-started/</a></p><h3>AWS — Official Documentation</h3><p>Amazon Web Services (AWS) is a leading <strong>cloud platform</strong>.</p><p>The AWS documentation provides guidance on:</p><ul><li>EC2 and virtual servers</li><li>S3 storage</li><li>IAM security</li><li>Deployment and scalability</li></ul><p>It is useful for:</p><ul><li>Hosting applications</li><li>Cloud infrastructure</li><li>Production deployments</li></ul><p>👉 Official link:<br> <a href="https://aws.amazon.com/documentation-overview/">https://aws.amazon.com/documentation-overview/</a></p><h3>PostgreSQL — Official Documentation</h3><p>PostgreSQL is a powerful <strong>open-source relational database</strong>.</p><p>The official documentation covers:</p><ul><li>SQL queries</li><li>Indexes and performance</li><li>Transactions</li><li>Advanced database features</li></ul><p>PostgreSQL is commonly used with:</p><ul><li>Django</li><li>Flask</li><li>FastAPI</li></ul><p>👉 Official link:<br> <a href="https://www.postgresql.org/docs/current/index.html">https://www.postgresql.org/docs/current/index.html</a></p><h3>Final Thoughts</h3><p>Official tutorials may look long, but they provide <strong>deep understanding</strong> and <strong>best practices</strong>.</p><p>If you are serious about backend development, always:</p><ul><li>Start with official docs</li><li>Practice alongside reading</li><li>Refer back when stuck</li></ul><p>Bookmark these links — they will help you throughout your career.</p><h3>Official Tutorials:-</h3><h4>Python Tutorial — <a href="https://docs.python.org/3/tutorial/index.html">https://docs.python.org/3/tutorial/index.html</a></h4><h4>Django Tutorial — <a href="https://docs.djangoproject.com/en/6.0/">https://docs.djangoproject.com/en/6.0/</a></h4><h4>Fast API Tutorial — <a href="https://fastapi.tiangolo.com/tutorial/">https://fastapi.tiangolo.com/tutorial/</a></h4><h4>Flask Tutorial — <a href="https://flask.palletsprojects.com/en/stable/">https://flask.palletsprojects.com/en/stable/</a></h4><h4>Docker Tutorial — <a href="https://docs.docker.com/get-started/">https://docs.docker.com/get-started/</a></h4><h4>AWS Tutorial — <a href="https://aws.amazon.com/documentation-overview/">https://aws.amazon.com/documentation-overview/</a></h4><h4>Postgresql — <a href="https://www.postgresql.org/docs/current/index.html">https://www.postgresql.org/docs/current/index.html</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c065cc9e76c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[django vs flask vs fastapi || Django || Flask || FastAPI||#Chapter-32]]></title>
            <link>https://medium.com/@sinturana07/django-vs-flask-vs-fastapi-django-flask-fastapi-chapter-32-4601f76aad8b?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/4601f76aad8b</guid>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 15:57:29 GMT</pubDate>
            <atom:updated>2026-02-02T15:57:29.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flask vs Fastapi vs Django</h3><p>🚀 **FastAPI: The Speed Racer**</p><p>Blazing fast and API-focused! ⚡ <br>With automatic OpenAPI docs, async support, and high performance, FastAPI is a dream for modern microservices and backend APIs.</p><p>🐍 **Django: The Full-Stack Maestro**</p><p>A complete web framework with all the bells and whistles! <br>From ORM to authentication and admin panel, Django is perfect for large-scale, complex applications following the MTV pattern.</p><p>🌶️ **Flask: The Spicy Minimalist**</p><p>Lightweight, flexible, and full of flavor! <br>Flask gives you the essentials and lets you pick the rest — ideal for smaller apps or when you want full control over your stack.</p><p>Which one’s your go-to Python web framework? Let’s hear your thoughts! 👇💬</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ShSR9nHNehPgL7VqNNwbyg.jpeg" /></figure><h3>Flask (Microframework)</h3><p>Flask is a <strong>lightweight Python web framework</strong>.</p><p>It is called a <strong>microframework</strong> because it provides only the basic tools to build a web application.<br> Flask does <strong>not include ORM, authentication, or admin panel</strong> by default.</p><p>Developers can add required features using external libraries like SQLAlchemy and Flask-Login.</p><p>Flask is <strong>easy to learn</strong> and gives <strong>full control</strong> over application structure.</p><p>It is suitable for:</p><ul><li>Small web applications</li><li>Simple REST APIs</li><li>Prototypes and MVPs</li></ul><p>Flask can be used as a <strong>monolithic app or microservice</strong>, depending on the design.</p><h3>FastAPI (Modern API Framework)</h3><p>FastAPI is a <strong>modern Python framework</strong> for building <strong>REST APIs</strong>.</p><p>It is known for <strong>high performance</strong> and <strong>async support</strong>.<br> FastAPI is built on <strong>ASGI</strong>, which makes it faster than Flask and Django.</p><p>It provides:</p><ul><li>Automatic API documentation (Swagger &amp; OpenAPI)</li><li>Request validation</li><li>Dependency injection</li></ul><p>FastAPI is commonly used in <strong>microservices architecture</strong>.</p><p>It is suitable for:</p><ul><li>High-performance APIs</li><li>Microservices</li><li>Machine learning and AI backends</li></ul><p>FastAPI is also a <strong>microframework</strong>, not monolithic.</p><h3>Django (Full-Stack Framework)</h3><p>Django is a <strong>full-stack Python web framework</strong>.</p><p>It follows a <strong>monolithic architecture by default</strong> and comes with many built-in features.</p><p>Django provides:</p><ul><li>ORM (Object Relational Mapper)</li><li>Authentication system</li><li>Admin panel</li><li>Middleware support</li></ul><p>Because everything is included, Django allows <strong>rapid development</strong>.</p><p>It is suitable for:</p><ul><li>Large applications</li><li>Enterprise projects</li><li>Content-heavy websites</li></ul><p>Django can be split into microservices, but it is <strong>naturally monolithic</strong>.</p><h3>Key Difference (Short Summary)</h3><ul><li>Flask is <strong>simple and flexible</strong></li><li>FastAPI is <strong>fast and API-focused</strong></li><li>Django is <strong>complete and powerful</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4601f76aad8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Redis Cache in Django for Storing Temporary Data||#Chapter-31]]></title>
            <link>https://medium.com/@sinturana07/how-to-use-redis-cache-in-django-for-storing-temporary-data-chapter-31-c8c471b02c59?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c471b02c59</guid>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 15:19:22 GMT</pubDate>
            <atom:updated>2026-01-15T15:19:22.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E75QXoQzCw02kGoT.jpg" /></figure><h3>How to Use Redis Cache in Django for Storing Temporary Data</h3><p>Caching is one of the best ways to improve performance and reduce database load in a Django application. When you need to store <strong>temporary data</strong> like OTPs, session info, API responses, or rate-limit counters, <strong>Redis</strong> is a perfect choice.</p><p>In this blog, you’ll learn how to integrate <strong>Redis cache</strong> in a Django project step by step.</p><h4>Why Use Redis with Django?</h4><p>Redis is an in-memory data store that is:</p><p>⚡ Extremely fast</p><p>🔐 Reliable</p><p>📈 Scalable</p><p>⏳ Perfect for temporary data</p><p>Common use cases:</p><p>OTP storage</p><p>Email/phone verification codes</p><p>API response caching</p><p>Rate limiting</p><p>Session storage</p><h4>Prerequisites</h4><p>Python 3.8+<br>Django project<br>Redis installed<br>Basic Django knowledge</p><h3>Make Your Django App Faster with Redis Caching (A Practical Guide)</h3><p>If your Django application feels slow, you’re not alone. Slow page loads, repeated database queries, and high server load are common problems as your app grows.</p><p>The good news?<br> You don’t need more servers.<br> You need <strong>better caching</strong> — and Redis is one of the best tools for that job.</p><p>In this guide, you’ll learn how to use <strong>Redis with Django</strong> to speed up your app the right way — not just how to install it, but how to <strong>use it effectively</strong>.</p><h3>Why Redis Works So Well with Django</h3><p>Redis stores data in memory instead of on disk, which makes it incredibly fast compared to database queries.</p><p>When used correctly, Redis can help you:</p><ul><li>Reduce database hits dramatically</li><li>Improve response times</li><li>Handle more users with the same infrastructure</li><li>Lower hosting costs</li><li>Build more scalable applications</li></ul><h3>Step 1: Install Redis</h3><h3>Linux (Ubuntu / Debian)</h3><pre>sudo apt update<br>sudo apt install redis-server<br>sudo systemctl start redis<br>sudo systemctl enable redis</pre><h3>macOS</h3><pre>brew install redis<br>brew services start redis</pre><h3>Windows</h3><p>Use <strong>WSL</strong> or install Redis from a trusted Windows port.</p><h3>Test Redis</h3><pre>redis-cli ping</pre><p>If you see <strong>PONG</strong>, Redis is running successfully.</p><p>Step 2: Install Required Python Packages</p><pre>pip install redis django-redis</pre><p>Add them to your requirements.txt:</p><pre>redis<br>django-redis</pre><h3>Step 3: Configure Redis in Django</h3><p>Open <strong>settings.py</strong> and add:</p><pre>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django_redis.cache.RedisCache&quot;,<br>        &quot;LOCATION&quot;: &quot;redis://127.0.0.1:6379/1&quot;,<br>        &quot;OPTIONS&quot;: {<br>            &quot;CLIENT_CLASS&quot;: &quot;django_redis.client.DefaultClient&quot;,<br>        },<br>        &quot;KEY_PREFIX&quot;: &quot;myproject&quot;,<br>        &quot;TIMEOUT&quot;: 300,<br>    }<br>}</pre><h3>What this means</h3><ul><li><strong>LOCATION</strong> → where Redis is running</li><li><strong>KEY_PREFIX</strong> → avoids conflicts when multiple apps share Redis</li><li><strong>TIMEOUT</strong> → default expiration time</li></ul><p>Step 4: Using Django Cache API</p><pre>from django.core.cache import cache<br><br># Save data<br>cache.set(&quot;welcome_msg&quot;, &quot;Hello Redis!&quot;, timeout=300)<br><br># Read data<br>msg = cache.get(&quot;welcome_msg&quot;)<br><br># Delete data<br>cache.delete(&quot;welcome_msg&quot;)</pre><h3>Step 5: Caching Real Data (Example: OTP)</h3><h3>Save OTP</h3><pre>import random<br>from django.core.cache import cache<br><br>def create_otp(phone):<br>    otp = random.randint(100000, 999999)<br>    cache.set(f&quot;otp:{phone}&quot;, otp, timeout=300)<br>    return otp</pre><p>Verify OTP</p><pre>def validate_otp(phone, user_input):<br>    saved_otp = cache.get(f&quot;otp:{phone}&quot;)<br>    if saved_otp and str(saved_otp) == str(user_input):<br>        cache.delete(f&quot;otp:{phone}&quot;)<br>        return True<br>    return False</pre><h3>Step 6: Cache Database Queries</h3><h3>Without caching</h3><p>Every request hits the database:</p><pre>def product_list(request):<br>    products = Product.objects.filter(active=True)<br>    return render(request, &quot;products.html&quot;, {&quot;products&quot;: products})</pre><h3>With caching</h3><pre>from django.core.cache import cache<br><br>def product_list(request):<br>    products = cache.get(&quot;active_products&quot;)<br><br>    if not products:<br>        products = list(Product.objects.filter(active=True))<br>        cache.set(&quot;active_products&quot;, products, timeout=600)<br><br>    return render(request, &quot;products.html&quot;, {&quot;products&quot;: products})</pre><p>Now your database is queried <strong>once every 10 minutes</strong>, not on every request.</p><h3>Step 7: Cache Entire Views</h3><pre>from django.views.decorators.cache import cache_page<br><br>@cache_page(60 * 10)<br>def home(request):<br>    return render(request, &quot;home.html&quot;)</pre><h3>Step 8: Cache Template Blocks</h3><pre>{% load cache %}<br><br>{% cache 600 navbar %}<br>  &lt;!-- heavy navbar logic --&gt;<br>{% endcache %}</pre><p>User-specific:</p><pre>{% cache 600 dashboard request.user.id %}</pre><h3>Step 9: Use Redis for Sessions</h3><pre>SESSION_ENGINE = &quot;django.contrib.sessions.backends.cache&quot;<br>SESSION_CACHE_ALIAS = &quot;default&quot;</pre><p>Now your sessions are:</p><ul><li>Faster</li><li>Automatically expired</li><li>Database-free</li></ul><h3>Step 10: Smart Caching Patterns</h3><h3>1. Cache-Aside Strategy</h3><pre>def get_profile(user_id):<br>    key = f&quot;profile:{user_id}&quot;<br>    data = cache.get(key)<br><br>    if not data:<br>        data = Profile.objects.get(user_id=user_id)<br>        cache.set(key, data, 3600)<br><br>    return data</pre><p>2. Auto Cache Invalidation</p><pre>from django.db.models.signals import post_save<br>from django.dispatch import receiver<br><br>@receiver(post_save, sender=Product)<br>def clear_product_cache(sender, instance, **kwargs):<br>    cache.delete(f&quot;product:{instance.id}&quot;)<br>    cache.delete(&quot;active_products&quot;)</pre><p>3. Cache Heavy Calculations</p><pre>def get_sales_report():<br>    key = &quot;monthly_sales&quot;<br>    data = cache.get(key)<br><br>    if not data:<br>        data = Order.objects.monthly_total()<br>        cache.set(key, data, 3600)<br><br>    return data</pre><h3>Step 11: Monitoring Redis</h3><pre>from django.core.cache import cache<br><br>client = cache.client.get_client()<br>stats = client.info()<br><br>print(stats[&quot;used_memory_human&quot;])<br>print(stats[&quot;connected_clients&quot;])</pre><h3>Best Practices for Production:</h3><p>✔ Cache what is read often</p><p>✔ Always set expiration time</p><p>✔ Use clear key names</p><p>✔ Handle cache failures safely</p><p>✔ Don’t store sensitive data without encryption</p><p>✔ Track cache hit ratio</p><h3>Common Mistakes:</h3><p>❌ Caching frequently changing values</p><p>❌ Using no expiration time</p><p>❌ Forgetting to clear cache when data updates</p><p>❌ Storing passwords or personal info in cache</p><p>Real-World Impact</p><p>After adding Redis caching to a medium-scale Django app:</p><p>Page load dropped from 1+ sec to under 200ms</p><p>Database load reduced by 80%</p><p>Server CPU usage cut in half</p><p>App handled 3x more users with same resources</p><h4><strong>Final Thoughts</strong></h4><p>Redis is not just a performance tool — it’s a scaling strategy.</p><p>If your Django app is growing and performance matters, Redis caching is one of the easiest and most powerful upgrades you can make.</p><h4>Start small:</h4><p>Cache one slow view</p><p>Cache one heavy query</p><p>Measure the difference</p><p>You’ll feel the speed immediately. 🚀</p><p>🔔 Follow for more Django &amp; Python blogs</p><p>👉 <a href="https://medium.com/@sinturana07">https://medium.com/@sinturana07</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c471b02c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twilio Account Setup & SMS Verification Using Twilio API in Django ||#Chapter-30]]></title>
            <link>https://medium.com/@sinturana07/twilio-account-setup-sms-verification-using-twilio-api-in-django-chapter-30-effa39f54dad?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/effa39f54dad</guid>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 14:55:22 GMT</pubDate>
            <atom:updated>2026-01-15T14:55:22.741Z</atom:updated>
            <content:encoded><![CDATA[<h3>SMS Verification Using Twilio API in Django — Step-by-Step Guide</h3><p>Phone number verification is an essential feature in modern applications for security, authentication, and fraud prevention. In this blog, we’ll implement <strong>SMS-based OTP verification</strong> in a Django project using the <strong>Twilio API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DcI2EBZEjb_feiJN.png" /></figure><p><strong>Why Use Twilio for SMS Verification?</strong></p><p>Twilio is a cloud communication platform that allows developers to send SMS, make calls, and build messaging workflows easily.</p><h4>Benefits:</h4><p>Reliable global SMS delivery<br>Easy API integration<br>Scalable and secure<br>Detailed delivery reports</p><p><strong>Prerequisites</strong></p><p>Before starting, make sure you have:</p><p>Python 3.9+</p><p>Django installed</p><p>A Twilio account</p><p>Basic knowledge of Django views &amp; models</p><p>Step 1: Create a Twilio Account</p><p>Go to <a href="https://www.twilio.com/">https://www.twilio.com/</a></p><p>Sign up and verify your email and phone number.</p><p>From the Twilio Console, copy:</p><p>Account SID</p><p>Auth Token</p><p>Buy a Twilio phone number for sending SMS.</p><h3>Step 2: Install Twilio SDK</h3><pre>pip install twilio</pre><h3>Step 3: Configure Twilio in Django</h3><p>Add these to your <strong>settings.py</strong>:</p><pre>TWILIO_ACCOUNT_SID = &quot;your_account_sid&quot;<br>TWILIO_AUTH_TOKEN = &quot;your_auth_token&quot;<br>TWILIO_PHONE_NUMBER = &quot;+1234567890&quot;</pre><p><strong>Tip: Use environment variables in production instead of hardcoding credentials.</strong></p><h3>Step 4: Create OTP Sender Utility</h3><p>Create a file: <strong>utils.py</strong></p><pre>import random<br>from twilio.rest import Client<br>from django.conf import settings<br><br>def generate_otp():<br>    return random.randint(100000, 999999)<br><br>def send_otp(phone_number, otp):<br>    client = Client(<br>        settings.TWILIO_ACCOUNT_SID,<br>        settings.TWILIO_AUTH_TOKEN<br>    )<br><br>    message = client.messages.create(<br>        body=f&quot;Your verification code is {otp}&quot;,<br>        from_=settings.TWILIO_PHONE_NUMBER,<br>        to=phone_number<br>    )<br>    return message.sid</pre><p>Step 5: Create OTP Model</p><pre>from django.db import models<br>from django.utils import timezone<br><br>class PhoneOTP(models.Model):<br>    phone = models.CharField(max_length=15)<br>    otp = models.CharField(max_length=6)<br>    created_at = models.DateTimeField(default=timezone.now)<br>    is_verified = models.BooleanField(default=False)</pre><p>Run migrations:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>Step 6: Send OTP View</p><pre>from django.shortcuts import render<br>from .models import PhoneOTP<br>from .utils import generate_otp, send_otp<br><br>def send_otp_view(request):<br>    if request.method == &quot;POST&quot;:<br>        phone = request.POST.get(&quot;phone&quot;)<br>        otp = generate_otp()<br><br>        PhoneOTP.objects.update_or_create(<br>            phone=phone,<br>            defaults={&quot;otp&quot;: otp, &quot;is_verified&quot;: False}<br>        )<br><br>        send_otp(phone, otp)<br>        return render(request, &quot;verify.html&quot;, {&quot;phone&quot;: phone})<br><br>    return render(request, &quot;send_otp.html&quot;)</pre><p>Step 7: Verify OTP View</p><pre>def verify_otp_view(request):<br>    if request.method == &quot;POST&quot;:<br>        phone = request.POST.get(&quot;phone&quot;)<br>        user_otp = request.POST.get(&quot;otp&quot;)<br><br>        try:<br>            record = PhoneOTP.objects.get(phone=phone)<br>            if record.otp == user_otp:<br>                record.is_verified = True<br>                record.save()<br>                return render(request, &quot;success.html&quot;)<br>            else:<br>                return render(request, &quot;verify.html&quot;, {&quot;error&quot;: &quot;Invalid OTP&quot;})<br>        except PhoneOTP.DoesNotExist:<br>            return render(request, &quot;verify.html&quot;, {&quot;error&quot;: &quot;OTP not found&quot;})</pre><p>Step 8: URLs Configuration</p><pre>from django.urls import path<br>from .views import send_otp_view, verify_otp_view<br><br>urlpatterns = [<br>    path(&quot;send-otp/&quot;, send_otp_view, name=&quot;send_otp&quot;),<br>    path(&quot;verify-otp/&quot;, verify_otp_view, name=&quot;verify_otp&quot;),<br>]</pre><p><strong>How the Flow Works:</strong></p><p>User enters phone number</p><p>Django generates OTP</p><p>Twilio sends OTP via SMS</p><p>User enters OTP</p><p>Django verifies OTP</p><p>Phone number verified ✅</p><h3>Security Best Practices:</h3><p>Expire OTP after 5 minutes</p><p>Limit OTP attempts</p><p>Use Redis or cache for temporary OTP storage</p><p>Never expose Twilio credentials in frontend</p><p>Enable HTTPS</p><h3>Conclusion</h3><p>Integrating SMS verification in Django using Twilio is simple, powerful, and production-ready. With just a few steps, you can add an extra layer of security to your application and improve user trust.</p><p>Twilio’s APIs combined with Django make it easy to build scalable authentication systems for startups and enterprise apps alike.</p><h3><a href="https://www.twilio.com/en-us/blog/server-notifications-python-django">SMS and MMS Notifications with Python and Django | Twilio</a></h3><p>Link — <a href="https://www.twilio.com/en-us/blog/server-notifications-python-django">https://www.twilio.com/en-us/blog/server-notifications-python-django</a></p><p><em>If you enjoyed this tutorial and want more Django &amp; Python blogs, please </em><strong><em>subscribe</em></strong><em> to my Medium profile:</em><br> 🔗 <a href="https://medium.com/@sinturana07">https://medium.com/@sinturana07</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=effa39f54dad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger Integration with Python Django || Django REST Framework Swagger || Swagger ||#Chapter-29]]></title>
            <link>https://medium.com/@sinturana07/swagger-integration-with-python-django-django-rest-framework-swagger-swagger-chapter-29-e8a59da97ab1?source=rss-ec29b600a9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8a59da97ab1</guid>
            <dc:creator><![CDATA[Sintu S@mson]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 08:36:54 GMT</pubDate>
            <atom:updated>2024-11-10T08:36:54.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_MlrdUdU_MhksKO3.png" /></figure><p>In Django, we can integrate Swagger to document APIs in various ways, primarily using popular libraries. <br>Each of these methods offers different levels of ease of integration, customization, and maintenance depending on your project’s requirements.</p><h4><strong>The main types of Swagger tools used in Django are:</strong></h4><p><strong>1.Django REST Swagger</strong>:</p><ul><li>One of the earlier libraries used for integrating Swagger with Django REST Framework.</li><li>Similar to drf-yasg, but with fewer features and less customization.</li><li>Somewhat deprecated, as it’s no longer actively maintained.</li><li>An alternative framework for building APIs, Django Ninja has Swagger support built-in.</li><li>Generates documentation directly from the view definitions, using OpenAPI and Pydantic for schema generation.</li><li>Suitable for projects looking for type annotations and validation via Pydantic models.</li></ul><h4><strong>2.Using </strong><strong>drf-spectacular</strong></h4><p>drf-spectacular is another tool that generates OpenAPI 3.0 documentation. It is a bit newer and is highly configurable. It also works seamlessly with Django REST Framework.</p><p>Installation</p><pre>pip install drf-spectacular</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*t_3nA4p487r8z97CmSq-4A.png" /></figure><p><strong>There are several ways to implement Swagger (OpenAPI) documentation in Django, especially with Django REST Framework (DRF). Here’s an overview of the main tools and methods:</strong></p><h3>Here’s how to create this task:-</h3><p>Step 1: Create a Django project in a blank folder<br>cmd: django-admin startproject project</p><p>Step 2: Open the project on V.S code.</p><p>Step 3: Create a Virtual Environment in the Django project.<br>cmd: virtualenv venv<br>cmd: pip freeze</p><p>Step 4: Activate the Virtual Environment<br>cmd: venv\scripts\activate</p><p>Step 5: Install The Django in the project.<br>cmd: pip install django</p><p>Step 6: Run the server<br>cmd: python manage.py runserver</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dNcA6ZS91VQuG2xF.png" /></figure><p>Step 7: Create the app in Django project.<br>cmd: python manage.py startapp app-name(app)</p><p>Step 8: Install the Django Rest Framework<br>cmd: pip install djangorestframework</p><p>Step 8: Register the app name inside the project settings.py file</p><pre># project - settings.py file<br># Application definition<br><br>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;app&#39;,<br>    &#39;rest_framework&#39;,<br>]</pre><p>Step 9: URL mapping of the app inside the project urls.py file</p><pre># project - urls.py file<br><br>from django.contrib import admin<br>from django.urls import path,include<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;app/&#39;, include(&#39;app.urls&#39;)),<br>]</pre><p>Step 10: Create urls.py new file inside the app</p><pre>#app - urls.py file<br><br>from django.urls import path<br>from app.views import *<br><br>urlpatterns = [<br>    <br>]</pre><p>Step 11: Run the Migration and migrate command to create Django tables.<br>cmd: python manage.py makemigrations<br>cmd: python manage.py migrate</p><p>Step12: Create Super User in Django<br>cmd: python manage.py createsuperuser</p><p>now we create simple api’s after that we use swagger</p><pre>from django.shortcuts import render<br>from rest_framework.response import Response<br>from rest_framework.decorators import api_view<br>from rest_framework.views import APIView<br><br># Create your views here.<br><br>@api_view([&#39;GET&#39;])<br>def first_view(request):<br>    return Response(&quot;First API Developed&quot;)<br><br><br><br>class Second(APIView):<br>    def get(self, request):<br>        return Response(&quot;Second API Developed&quot;)</pre><pre>from django.urls import path<br>from app.views import *<br><br>urlpatterns = [<br>    path(&#39;demo/&#39;,first_view, name=&#39;demo&#39;),<br>    path(&#39;second/&#39;, Second.as_view(), name=&#39;first_view&#39;),<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFocq3us5MC5tANuD2AjZA.png" /></figure><p>There are several ways to implement Swagger (OpenAPI) documentation in Django, especially with Django REST Framework (DRF). Here’s an overview of the main tools and methods:</p><h3>1. drf-yasg (Yet Another Swagger Generator)</h3><p><strong>drf-yasg</strong> is a popular tool that integrates seamlessly with DRF and provides a robust way to generate Swagger and ReDoc documentation for APIs.</p><p>Steps to Use drf-yasg:</p><pre>pip install drf-yasg</pre><p>Update settings.py</p><pre># Application definition<br><br>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;app&#39;,<br>    &#39;rest_framework&#39;,<br>    &#39;drf_yasg&#39;,<br>    <br>]<br><br># Optional: Define the path for static files (if necessary)<br>STATICFILES_DIRS = [<br>    BASE_DIR / &quot;static&quot;,<br>]<br><br></pre><p>Update your urls.py</p><pre>from django.contrib import admin<br>from django.urls import path,include<br><br>from rest_framework import permissions<br>from drf_yasg.views import get_schema_view<br>from drf_yasg import openapi<br><br>schema_view = get_schema_view(<br>    openapi.Info(<br>        title=&quot;Your API Title&quot;,<br>        default_version=&#39;v1&#39;,<br>        description=&quot;API documentation&quot;,<br>    ),<br>    public=True,<br>    permission_classes=(permissions.AllowAny,),<br>)<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;app/&#39;,include(&#39;app.urls&#39;)),<br>    path(&#39;swagger/&#39;, schema_view.with_ui(&#39;swagger&#39;, cache_timeout=0), name=&#39;schema-swagger-ui&#39;),<br>    path(&#39;redoc/&#39;, schema_view.with_ui(&#39;redoc&#39;, cache_timeout=0), name=&#39;schema-redoc&#39;),<br>]</pre><p>cmd: python manage.py runserver</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vw2wR714N2Dojktf-eaHwA.png" /><figcaption><a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OH2ogJeOlDIEr0MQHWIXWQ.png" /><figcaption><a href="http://127.0.0.1:8000/swagger/">Your API Title</a></figcaption></figure><h3>2.Using drf-spectacular</h3><p>drf-spectacular is another tool that generates OpenAPI 3.0 documentation. It is a bit newer and is highly configurable. It also works seamlessly with Django REST Framework.</p><p>Installation</p><pre>pip install drf-spectacular</pre><p>Update settings.py</p><pre># Application definition<br><br>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;app&#39;,<br>    &#39;rest_framework&#39;,<br>    &#39;drf_spectacular&#39;,<br>]<br><br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_SCHEMA_CLASS&#39;: &#39;drf_spectacular.openapi.AutoSchema&#39;,<br>}</pre><p>Update your project urls.py</p><pre>from django.contrib import admin<br>from django.urls import path,include<br><br>from rest_framework import permissions<br>from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;app/&#39;,include(&#39;app.urls&#39;)),<br>    path(&#39;schema/&#39;, SpectacularAPIView.as_view(), name=&#39;schema&#39;),  # OpenAPI schema<br>    path(&#39;swagger/&#39;, SpectacularSwaggerView.as_view(url_name=&#39;schema&#39;), name=&#39;swagger-ui&#39;),<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9P_ngQlFUSi21-SYzHMUQ.png" /><figcaption><a href="http://127.0.0.1:8000/">Page not found at /</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2MXXk4RWGWJ9vbt4L2tcQ.png" /><figcaption><a href="http://127.0.0.1:8000/swagger/">Swagger</a></figcaption></figure><p>Many other methods are available, but I have explained two methods that are generally used by almost all developers in an organization</p><p><a href="https://medium.com/@sinturana07">https://medium.com/@sinturana07</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8a59da97ab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>