<?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 theamanshakya on Medium]]></title>
        <description><![CDATA[Stories by theamanshakya on Medium]]></description>
        <link>https://medium.com/@theamanshakya?source=rss-de103ade0757------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ABA-1RIEihsx7521.jpg</url>
            <title>Stories by theamanshakya on Medium</title>
            <link>https://medium.com/@theamanshakya?source=rss-de103ade0757------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:44:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theamanshakya/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[FastAPI Interview Preparation Guide 2025]]></title>
            <link>https://medium.com/@theamanshakya/fastapi-interview-preparation-guide-2025-bdf2b468c753?source=rss-de103ade0757------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf2b468c753</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[theamanshakya]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 22:26:45 GMT</pubDate>
            <atom:updated>2025-06-10T22:26:45.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What is FastAPI, and how does it differ from other web frameworks?</h3><p><strong>FastAPI</strong> is a modern, fast web framework for building APIs with Python 3.7+ based on standard Python type hints. It was created by Sebastian Ramirez in 2018.</p><h3>Key Differences from Other Frameworks:</h3><p><strong>vs Flask:</strong></p><ul><li>FastAPI has automatic API documentation (OpenAPI/Swagger)</li><li>Built-in data validation using Pydantic</li><li>Async support by default</li><li>Type hints for better IDE support and validation</li></ul><p><strong>vs Django REST Framework:</strong></p><ul><li>FastAPI is lighter and more focused on APIs</li><li>Better performance (one of the fastest Python frameworks)</li><li>Simpler setup for API-only applications</li><li>Built-in async support</li></ul><p><strong>vs Express.js (Node.js):</strong></p><ul><li>Comparable performance</li><li>Automatic data validation and serialization</li><li>Built-in documentation generation</li></ul><h3>2. Benefits of Using FastAPI</h3><ul><li><strong>High Performance</strong>: Comparable to Node.js and Go</li><li><strong>Fast Development</strong>: Reduces development time by 200–300%</li><li><strong>Fewer Bugs</strong>: Reduces human-induced errors by ~40%</li><li><strong>Intuitive</strong>: Great editor support with autocompletion</li><li><strong>Easy</strong>: Designed to be easy to learn and use</li><li><strong>Short</strong>: Minimize code duplication</li><li><strong>Robust</strong>: Production-ready code with automatic documentation</li><li><strong>Standards-based</strong>: Based on OpenAPI and JSON Schema</li><li><strong>Async Support</strong>: Native async/await support</li></ul><h3>3. How FastAPI Handles Requests and Responses</h3><p>FastAPI uses <strong>ASGI</strong> (Asynchronous Server Gateway Interface) to handle requests asynchronously:</p><ol><li><strong>Request Processing</strong>: Incoming requests are parsed and validated against type hints</li><li><strong>Path Operation</strong>: Routes requests to appropriate path operation functions</li><li><strong>Dependency Injection</strong>: Resolves dependencies before executing the handler</li><li><strong>Data Validation</strong>: Automatically validates request data using Pydantic models</li><li><strong>Response Generation</strong>: Serializes response data and generates appropriate HTTP responses</li></ol><h3>4. Route Definition Syntax</h3><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre># Basic GET route<br>@app.get(&quot;/&quot;)<br>def read_root():<br>    return {&quot;Hello&quot;: &quot;World&quot;}</pre><pre># Route with path parameter<br>@app.get(&quot;/items/{item_id}&quot;)<br>def read_item(item_id: int, q: str = None):<br>    return {&quot;item_id&quot;: item_id, &quot;q&quot;: q}</pre><pre># POST route with request body<br>@app.post(&quot;/items/&quot;)<br>def create_item(item: Item):<br>    return item</pre><h3>5. Types of Request Parameters</h3><h3>Path Parameters</h3><pre>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    return {&quot;user_id&quot;: user_id}</pre><h3>Query Parameters</h3><pre>@app.get(&quot;/items/&quot;)<br>def read_items(skip: int = 0, limit: int = 10):<br>    return {&quot;skip&quot;: skip, &quot;limit&quot;: limit}</pre><h3>Request Body</h3><pre>from pydantic import BaseModel</pre><pre>class Item(BaseModel):<br>    name: str<br>    price: float</pre><pre>@app.post(&quot;/items/&quot;)<br>def create_item(item: Item):<br>    return item</pre><h3>Headers</h3><pre>from fastapi import Header</pre><pre>@app.get(&quot;/items/&quot;)<br>def read_items(user_agent: str = Header(None)):<br>    return {&quot;User-Agent&quot;: user_agent}</pre><h3>Cookies</h3><pre>from fastapi import Cookie</pre><pre>@app.get(&quot;/items/&quot;)<br>def read_items(session_id: str = Cookie(None)):<br>    return {&quot;session_id&quot;: session_id}</pre><h3>6. Dependency Injection in FastAPI</h3><p>Dependency Injection is a design pattern where components receive their dependencies from external sources rather than creating them internally. FastAPI has a powerful dependency injection system.</p><p><strong>Benefits:</strong></p><ul><li>Code reusability</li><li>Easy testing</li><li>Separation of concerns</li><li>Automatic validation</li></ul><h3>7. Defining and Using Dependencies</h3><pre>from fastapi import Depends</pre><pre># Simple dependency<br>def common_parameters(q: str = None, skip: int = 0, limit: int = 100):<br>    return {&quot;q&quot;: q, &quot;skip&quot;: skip, &quot;limit&quot;: limit}</pre><pre>@app.get(&quot;/items/&quot;)<br>def read_items(commons: dict = Depends(common_parameters)):<br>    return commons</pre><pre># Class-based dependency<br>class CommonQueryParams:<br>    def __init__(self, q: str = None, skip: int = 0, limit: int = 100):<br>        self.q = q<br>        self.skip = skip<br>        self.limit = limit</pre><pre>@app.get(&quot;/users/&quot;)<br>def read_users(commons: CommonQueryParams = Depends(CommonQueryParams)):<br>    return commons</pre><h3>8. Middleware in FastAPI</h3><p>Middleware is a function that works with every request before it’s processed by specific path operations and with every response before returning it.</p><p><strong>Common Use Cases:</strong></p><ul><li>Authentication</li><li>Logging</li><li>CORS handling</li><li>Request/Response modification</li><li>Performance monitoring</li></ul><h3>9. Adding Middleware</h3><pre>from fastapi import FastAPI, Request<br>import time</pre><pre>app = FastAPI()</pre><pre>@app.middleware(&quot;http&quot;)<br>async def add_process_time_header(request: Request, call_next):<br>    start_time = time.time()<br>    response = await call_next(request)<br>    process_time = time.time() - start_time<br>    response.headers[&quot;X-Process-Time&quot;] = str(process_time)<br>    return response</pre><pre># Using third-party middleware<br>from fastapi.middleware.cors import CORSMiddleware</pre><pre>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)</pre><h3>10. Path Parameters vs Query Parameters</h3><h3>Path Parameters</h3><ul><li>Part of the URL path</li><li>Required by default</li><li>Declared in the path string with {parameter_name}</li><li>Example: /users/{user_id} → user_id is a path parameter</li></ul><h3>Query Parameters</h3><ul><li>Come after ? in the URL</li><li>Optional by default (can be made required)</li><li>Declared as function parameters</li><li>Example: /users?skip=0&amp;limit=10 → skip and limit are query parameters</li></ul><h3>11. Exception and Error Handling</h3><pre>from fastapi import HTTPException</pre><pre>@app.get(&quot;/items/{item_id}&quot;)<br>def read_item(item_id: str):<br>    if item_id not in items:<br>        raise HTTPException(status_code=404, detail=&quot;Item not found&quot;)<br>    return {&quot;item&quot;: items[item_id]}</pre><pre># Custom exception handler<br>from fastapi.responses import JSONResponse</pre><pre>class UnicornException(Exception):<br>    def __init__(self, name: str):<br>        self.name = name</pre><pre>@app.exception_handler(UnicornException)<br>async def unicorn_exception_handler(request: Request, exc: UnicornException):<br>    return JSONResponse(<br>        status_code=418,<br>        content={&quot;message&quot;: f&quot;Oops! {exc.name} did something.&quot;}<br>    )</pre><h3>12. Handling CORS</h3><pre>from fastapi.middleware.cors import CORSMiddleware</pre><pre>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;http://localhost:3000&quot;, &quot;https://mydomain.com&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;GET&quot;, &quot;POST&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)</pre><h3>13. Pydantic in FastAPI</h3><p><strong>Pydantic</strong> is a Python library that provides data validation and settings management using Python type annotations.</p><p><strong>Usage in FastAPI:</strong></p><ul><li>Request body validation</li><li>Response model definition</li><li>Configuration management</li><li>Data serialization/deserialization</li></ul><pre>from pydantic import BaseModel, validator<br>from typing import Optional</pre><pre>class User(BaseModel):<br>    name: str<br>    email: str<br>    age: Optional[int] = None<br>    <br>    @validator(&#39;email&#39;)<br>    def email_must_contain_at(cls, v):<br>        if &#39;@&#39; not in v:<br>            raise ValueError(&#39;Invalid email&#39;)<br>        return v</pre><h3>14. Response Model Syntax</h3><pre>from pydantic import BaseModel</pre><pre>class Item(BaseModel):<br>    name: str<br>    price: float<br>    is_offer: bool = False</pre><pre>class ItemResponse(BaseModel):<br>    name: str<br>    price: float</pre><pre>@app.post(&quot;/items/&quot;, response_model=ItemResponse)<br>def create_item(item: Item):<br>    return item</pre><pre># Response model with list<br>from typing import List</pre><pre>@app.get(&quot;/items/&quot;, response_model=List[ItemResponse])<br>def read_items():<br>    return items</pre><h3>15. Background Tasks</h3><p>Background tasks allow you to run functions after returning a response, useful for operations that don’t need to complete before returning the response.</p><p><strong>Use Cases:</strong></p><ul><li>Sending emails</li><li>Processing files</li><li>Logging</li><li>Cache warming</li></ul><h3>16. Using Background Tasks</h3><pre>from fastapi import BackgroundTasks</pre><pre>def write_log(message: str):<br>    with open(&quot;log.txt&quot;, &quot;a&quot;) as log:<br>        log.write(message)</pre><pre>@app.post(&quot;/send-notification/&quot;)<br>async def send_notification(email: str, background_tasks: BackgroundTasks):<br>    background_tasks.add_task(write_log, f&quot;Notification sent to {email}&quot;)<br>    return {&quot;message&quot;: &quot;Notification sent in the background&quot;}</pre><pre># Multiple background tasks<br>@app.post(&quot;/process-items/&quot;)<br>async def process_items(background_tasks: BackgroundTasks):<br>    background_tasks.add_task(task_one, &quot;arg1&quot;)<br>    background_tasks.add_task(task_two, &quot;arg2&quot;, keyword=&quot;value&quot;)<br>    return {&quot;message&quot;: &quot;Tasks started&quot;}</pre><h3>17. WebSocket Purpose in FastAPI</h3><p>WebSockets enable <strong>bidirectional, real-time communication</strong> between client and server.</p><p><strong>Use Cases:</strong></p><ul><li>Chat applications</li><li>Live notifications</li><li>Real-time dashboards</li><li>Gaming applications</li><li>Live data feeds</li></ul><h3>18. Implementing WebSockets</h3><pre>from fastapi import WebSocket, WebSocketDisconnect</pre><pre>@app.websocket(&quot;/ws&quot;)<br>async def websocket_endpoint(websocket: WebSocket):<br>    await websocket.accept()<br>    try:<br>        while True:<br>            data = await websocket.receive_text()<br>            await websocket.send_text(f&quot;Message text was: {data}&quot;)<br>    except WebSocketDisconnect:<br>        print(&quot;Client disconnected&quot;)</pre><pre># WebSocket with path parameters<br>@app.websocket(&quot;/ws/{client_id}&quot;)<br>async def websocket_endpoint(websocket: WebSocket, client_id: int):<br>    await websocket.accept()<br>    # Handle client-specific logic</pre><h3>19. OAuth2 and JWT Authentication Support</h3><p>FastAPI provides built-in support for OAuth2 with JWT tokens:</p><pre>from fastapi import Depends, HTTPException, status<br>from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm<br>from jose import JWTError, jwt<br>from passlib.context import CryptContext</pre><pre>oauth2_scheme = OAuth2PasswordBearer(tokenUrl=&quot;token&quot;)<br>pwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)</pre><pre>SECRET_KEY = &quot;your-secret-key&quot;<br>ALGORITHM = &quot;HS256&quot;</pre><pre>def create_access_token(data: dict):<br>    return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)</pre><pre>async def get_current_user(token: str = Depends(oauth2_scheme)):<br>    try:<br>        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])<br>        username: str = payload.get(&quot;sub&quot;)<br>        if username is None:<br>            raise HTTPException(status_code=401, detail=&quot;Invalid token&quot;)<br>        return username<br>    except JWTError:<br>        raise HTTPException(status_code=401, detail=&quot;Invalid token&quot;)</pre><pre>@app.get(&quot;/protected&quot;)<br>async def protected_route(current_user: str = Depends(get_current_user)):<br>    return {&quot;user&quot;: current_user}</pre><h3>20. Securing FastAPI Applications</h3><h3>Authentication Methods:</h3><ul><li>JWT tokens</li><li>OAuth2</li><li>API keys</li><li>Basic authentication</li></ul><h3>Security Best Practices:</h3><pre>from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials<br>from fastapi import Depends, HTTPException</pre><pre>security = HTTPBearer()</pre><pre>async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):<br>    if not verify_jwt_token(credentials.credentials):<br>        raise HTTPException(status_code=401, detail=&quot;Invalid token&quot;)<br>    return credentials.credentials</pre><pre># Rate limiting<br>from slowapi import Limiter, _rate_limit_exceeded_handler<br>from slowapi.util import get_remote_address</pre><pre>limiter = Limiter(key_func=get_remote_address)<br>app.state.limiter = limiter<br>app.add_exception_handler(429, _rate_limit_exceeded_handler)</pre><pre>@app.get(&quot;/limited&quot;)<br>@limiter.limit(&quot;5/minute&quot;)<br>async def limited_endpoint(request: Request):<br>    return {&quot;message&quot;: &quot;This endpoint is rate limited&quot;}</pre><h3>21. Benefits of Using FastAPI with Docker</h3><ul><li><strong>Consistent Environment</strong>: Same environment across development, testing, and production</li><li><strong>Easy Deployment</strong>: Containerized applications are easier to deploy</li><li><strong>Scalability</strong>: Easy horizontal scaling with container orchestration</li><li><strong>Isolation</strong>: Dependencies are isolated within containers</li><li><strong>Portability</strong>: Runs anywhere Docker is supported</li></ul><pre>FROM python:3.9</pre><pre>WORKDIR /app</pre><pre>COPY requirements.txt .<br>RUN pip install -r requirements.txt</pre><pre>COPY . .</pre><pre>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><h3>22. Deploying to Cloud Platforms</h3><h3>AWS Deployment Options:</h3><ul><li><strong>AWS Lambda</strong> (serverless)</li><li><strong>AWS ECS/EKS</strong> (containerized)</li><li><strong>AWS Elastic Beanstalk</strong> (platform-as-a-service)</li><li><strong>AWS EC2</strong> (virtual machines)</li></ul><h3>Heroku Deployment:</h3><pre># Procfile<br>web: uvicorn main:app --host=0.0.0.0 --port=${PORT:-5000}</pre><pre># Deploy commands<br>heroku create myapp<br>git push heroku main</pre><h3>Key Considerations:</h3><ul><li>Environment variables for configuration</li><li>Database connections</li><li>Static file serving</li><li>HTTPS/SSL certificates</li><li>Load balancing</li></ul><h3>23. Testing Support</h3><p>FastAPI provides excellent testing support with TestClient:</p><pre>from fastapi.testclient import TestClient<br>from main import app</pre><pre>client = TestClient(app)</pre><pre>def test_read_main():<br>    response = client.get(&quot;/&quot;)<br>    assert response.status_code == 200<br>    assert response.json() == {&quot;Hello&quot;: &quot;World&quot;}</pre><pre>def test_create_item():<br>    response = client.post(<br>        &quot;/items/&quot;,<br>        json={&quot;name&quot;: &quot;Foo&quot;, &quot;price&quot;: 50.5}<br>    )<br>    assert response.status_code == 200<br>    assert response.json()[&quot;name&quot;] == &quot;Foo&quot;</pre><pre># Testing with authentication<br>def test_protected_endpoint():<br>    headers = {&quot;Authorization&quot;: &quot;Bearer valid-token&quot;}<br>    response = client.get(&quot;/protected&quot;, headers=headers)<br>    assert response.status_code == 200</pre><h3>24. Best Practices for Development and Deployment</h3><h3>Development Best Practices:</h3><ul><li>Use type hints consistently</li><li>Implement proper error handling</li><li>Use Pydantic models for data validation</li><li>Organize code with routers</li><li>Write comprehensive tests</li><li>Use environment variables for configuration</li><li>Implement logging</li><li>Use dependency injection for reusable components</li></ul><h3>Deployment Best Practices:</h3><ul><li>Use HTTPS in production</li><li>Set up proper monitoring and logging</li><li>Implement health checks</li><li>Use environment-specific configurations</li><li>Set up CI/CD pipelines</li><li>Use secrets management</li><li>Implement rate limiting</li><li>Regular security updates</li></ul><h3>Code Organization:</h3><pre>app/<br>├── main.py<br>├── models/<br>│   ├── __init__.py<br>│   └── user.py<br>├── routers/<br>│   ├── __init__.py<br>│   ├── users.py<br>│   └── items.py<br>├── dependencies/<br>│   ├── __init__.py<br>│   └── auth.py<br>└── tests/<br>    ├── __init__.py<br>    └── test_main.py</pre><h3>25. Scalability and Performance</h3><h3>Performance Features:</h3><ul><li><strong>Async/Await Support</strong>: Non-blocking I/O operations</li><li><strong>High Performance</strong>: One of the fastest Python frameworks</li><li><strong>Automatic Validation</strong>: Reduces overhead of manual validation</li><li><strong>Efficient Serialization</strong>: Pydantic’s optimized serialization</li></ul><h3>Scalability Strategies:</h3><ul><li><strong>Horizontal Scaling</strong>: Multiple instances behind a load balancer</li><li><strong>Database Optimization</strong>: Connection pooling, query optimization</li><li><strong>Caching</strong>: Redis, Memcached for frequently accessed data</li><li><strong>CDN</strong>: Content delivery networks for static assets</li><li><strong>Monitoring</strong>: Application performance monitoring (APM)</li></ul><h3>Performance Tips:</h3><pre># Use async for I/O operations<br>@app.get(&quot;/async-endpoint&quot;)<br>async def async_endpoint():<br>    data = await fetch_data_from_database()<br>    return data</pre><pre># Use background tasks for non-critical operations<br>@app.post(&quot;/process-data&quot;)<br>async def process_data(background_tasks: BackgroundTasks):<br>    background_tasks.add_task(heavy_processing_task)<br>    return {&quot;status&quot;: &quot;processing started&quot;}</pre><pre># Implement caching<br>from functools import lru_cache</pre><pre>@lru_cache()<br>def get_settings():<br>    return Settings()</pre><h3>Interview Tips</h3><ol><li><strong>Practice Code Examples</strong>: Be ready to write basic FastAPI code on a whiteboard or computer</li><li><strong>Understand Async</strong>: Be prepared to explain when and why to use async/await</li><li><strong>Know the Ecosystem</strong>: Understand how FastAPI fits with other Python tools (SQLAlchemy, Alembic, etc.)</li><li><strong>Real-world Experience</strong>: Prepare examples of how you’ve used or would use FastAPI in real projects</li><li><strong>Compare with Other Frameworks</strong>: Be ready to discuss trade-offs between FastAPI and other frameworks</li><li><strong>Security Awareness</strong>: Understand common web security concerns and how FastAPI addresses them</li></ol><p>Good luck with your interview!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf2b468c753" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>