<?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 Yesha Vyas on Medium]]></title>
        <description><![CDATA[Stories by Yesha Vyas on Medium]]></description>
        <link>https://medium.com/@yeshavyas27?source=rss-ee2ae7e104e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S14U_G1AjOILV1FYScPsbQ@2x.jpeg</url>
            <title>Stories by Yesha Vyas on Medium</title>
            <link>https://medium.com/@yeshavyas27?source=rss-ee2ae7e104e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:47:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yeshavyas27/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[A Gentle Introduction to FastAPI]]></title>
            <link>https://medium.com/@yeshavyas27/a-gentle-introduction-to-fastapi-99b9f48294af?source=rss-ee2ae7e104e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b9f48294af</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Yesha Vyas]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 11:09:10 GMT</pubDate>
            <atom:updated>2025-04-15T02:27:30.726Z</atom:updated>
            <content:encoded><![CDATA[<p>FastAPI is a python based web framework for building APIs. Its tagline promises:</p><blockquote><strong><em>high performance, easy to learn, fast to code, ready for production.</em></strong></blockquote><p>Big claims, right? Let’s dive in and see how it delivers on these promises.</p><h3>Why would you use FastAPI?</h3><p>What makes FastAPI stand out to me is its focus on developer productivity and performance. You don’t have to write code that is not core to your functionality (like type validations, conversions, and parsing) while still maintaining good practice, because FastAPI handles it for you. For example, if the client sends a text where a number is expected, FastAPI will handle that and return a response that says it expects a valid number, if it is not a number, your server won’t crash even if you have not raised an exception for this.</p><p>Here are some of the reasons I enjoy working with it:</p><ul><li><strong>Automatic Request Parsing and Data Validation</strong>: FastAPI automatically validates and parses query parameters, path parameters, and request bodies. It also validates specific data inside the request body (which is achieved by defining the request body in Pydantic models). No need to write manual checks for data types or conversions.</li><li><strong>Built-in OpenAPI Documentation</strong>: FastAPI generates interactive API documentation at /docs using Swagger UI. You can test endpoints directly here, bye bye Postman.</li><li><strong>Asynchronous Support</strong>: You can use both async and sync functions. In the majority of use cases, using async is generally better.</li><li><strong>Editor Support</strong>: With type hints, FastAPI provides excellent autocompletion and error detection in editors like VS Code.</li><li><strong>Automatic Response Conversion</strong>: Responses are automatically converted to JSON or other formats based on the defined model.</li><li><strong>Support for Standard HTTP Methods</strong>: Includes all standard methods like GET, POST, PUT, DELETE, etc.</li><li><strong>Intuitive Design</strong>: The framework is simple yet powerful, letting you focus on the business logic.</li></ul><h3>Getting Started with FastAPI</h3><p>To start using FastAPI, you first need to install it: (shit sherlock)</p><pre>pip install fastapi[standard]</pre><h3>Creating Your First Endpoint</h3><p>You create an instance of the FastAPI class as below, and use it as a decorator function to indicate the endpoint, and you attach it above the function that will handle that particular endpoint’s request:</p><p>Here’s how you can create a simple “Hello World” API:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><ul><li>@app.get(&quot;/&quot;)This decorator tells FastAPI to handle GET requests at the root path (/).</li><li>The function below processes the request and returns a JSON response.</li></ul><p>To run this app, in the command line write:</p><pre>fastapi dev &lt;filename&gt;</pre><p>If your filename is app.py, then:</p><pre>fastapi dev app.py</pre><p>Visit http://127.0.0.1:8000/ in your browser or API client to see the response.</p><h3>Core Concepts</h3><h4>Path Parameters</h4><p>Path parameters allow you to handle dynamic URLs. For example:</p><pre>@app.get(&quot;/users/{user_id}&quot;)<br>async def read_user(user_id: int):<br>    return {&quot;user_id&quot;: user_id}</pre><p>Here:</p><ul><li>{user_id} in the URL is captured as a path parameter.</li><li>The type hint (int) ensures validation, and with this info, FastAPI converts it to an integer data type on its own.</li><li>You can also use Path() to define a Path parameter.</li></ul><p>Order matters with path operations:</p><pre>@app.get(&quot;/users/me&quot;)  # Specific path<br>@app.get(&quot;/users/{user_id}&quot;)  # Dynamic path</pre><p>The more specific route should always come first.</p><h4>Query Parameters</h4><p>Query parameters are appended to the URL after a ?. For example:</p><pre>@app.get(&quot;/items&quot;)<br>async def read_items(skip: int = 0, limit: int = 10):<br>    return {&quot;skip&quot;: skip, &quot;limit&quot;: limit}</pre><p>This handles requests like /items?skip=20&amp;limit=30. You can also use Query() to define a query parameter.</p><h4>Request Body</h4><p>FastAPI uses Pydantic models for defining and validating request bodies:</p><pre>from pydantic import BaseModel<br><br>class Item(BaseModel):<br>    name: str<br>    description: str | None = None<br>    price: float<br>    tax: float | None = None<br><br>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item):<br>    return item</pre><p>Note: You can also declare some fields as optional by setting their default value as None, like in ‘description: str | None = None’. This also applies to things like query, cookie, header, etc.</p><p>Pydantic models support:</p><ul><li>Field validation (e.g., required fields and their data types).</li><li>Nested models. (e.g., a model has a field which is of the data type of another Pydantic model.)</li><li>Default values.</li></ul><p>Similarly, you can use Body() to define body data as:</p><pre>from typing import Annotated<br><br>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Annotated[Item, Body()]):<br>    return item</pre><p>This tells FastAPI that the ‘item’ is sent in the request body and it should be of type ‘Item’, which is a Pydantic model we defined.</p><h4>Response Models</h4><p>You can define the structure of your responses using Pydantic models:</p><pre>from pydantic import BaseModel<br><br>class Item(BaseModel):<br>    name: str<br>    price: float<br>@app.post(&quot;/items/&quot;, response_model=Item)<br>async def create_item(item: Item):<br>    return item</pre><p>Benefits:</p><ul><li>Validates response data.</li><li>Filters out extra fields not defined in the model.</li></ul><p>Alternatively, you can also declare the response type as:</p><pre>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item) -&gt; Item:<br>    return item</pre><h4>Status Codes</h4><p>Set HTTP status codes for responses:</p><pre>from fastapi import status<br><br>@app.post(&quot;/items/&quot;, status_code=status.HTTP_201_CREATED)<br>async def create_item(item: Item):<br>    return item</pre><p>The ‘status’ imported from FastAPI has all sorts of status codes defined in it, for example:</p><ul><li>200: status.HTTP_200_OK</li><li>403: status.HTTP_403_FORBIDDEN</li><li>and so on</li></ul><h4>Error Handling</h4><p>Raise HTTP exceptions when needed:</p><pre>from fastapi import HTTPException, status<br><br>@app.get(&quot;/items/{item_id}&quot;)<br>async def read_item(item_id: int):<br>    if item_id not in items:<br>        raise HTTPException(<br>                status_code=status.HTTP_404_NOT_FOUND , <br>                detail=&quot;Item not found&quot;<br>                )<br>    return {&quot;item&quot;: items[item_id]}</pre><p>This also works for functions in other files that are called in the endpoint function. You can just raise the HTTPException there, and it will be returned in the response.</p><h4>Cookies:</h4><p>Access cookies using the Cookie parameter type.</p><pre>from fastapi import Cookie<br><br>@app.get(&quot;/items/&quot;)<br>async def read_items(ads_id: int = Cookie(None)):<br>    return {&quot;ads_id&quot;: ads_id}</pre><h4>Headers:</h4><p>Access headers similarly using Header.</p><pre>from fastapi import Header<br><br>@app.get(&quot;/items/&quot;)<br>async def read_items(x_token: list[str] | None = Header(None)):<br>    return {&quot;X-Token values&quot;: x_token}</pre><h3>Additional Features</h3><p>FastAPI also supports:</p><ul><li><strong>Dependencies</strong> for shared logic, like database connections or authentication.</li><li><strong>Security</strong> features like OAuth2 with JWT tokens.</li><li><strong>APIRouter</strong> for modularizing large applications.</li><li><strong>Middleware</strong> for processing requests globally.</li><li><strong>Metadata </strong>can be added to all classes, like Path, Query, Body, and more. This data is reflected in the documentation.</li></ul><h3>Conclusion</h3><p>FastAPI is an excellent choice for building APIs. Its automatic validation, built-in documentation, and support for modern Python features make development faster and more enjoyable.</p><p>I highly recommend referring to the <a href="https://fastapi.tiangolo.com/tutorial/">FastAPI User Guide</a> as you build your projects. Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b9f48294af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>