studygyaan.com
Open in
urlscan Pro
2606:4700:3033::6815:39cf
Public Scan
URL:
https://studygyaan.com/cheatsheet/fastapi
Submission: On April 05 via manual from IN — Scanned from DE
Submission: On April 05 via manual from IN — Scanned from DE
Form analysis
2 forms found in the DOMhttps://studygyaan.com/
<form class="shortcode-search-form" role="search" action="https://studygyaan.com/"><input class="shortcode-search-input" placeholder="Type cheatsheet, code" type="search" name="s" required="">
<button class="shortcode-search-button" aria-label="Search">Search</button>
</form>
https://studygyaan.com/
<form role="search" class="search-modal-form" action="https://studygyaan.com/"><label for="search-modal-input" class="screen-reader-text">Search for:</label>
<div class="search-modal-fields"><input id="search-modal-input" type="search" class="search-field" placeholder="Search …" name="s">
<button aria-label="Search"><span class="gp-icon icon-search"><svg viewBox="0 0 512 512" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em">
<path fill-rule="evenodd" clip-rule="evenodd"
d="M208 48c-88.366 0-160 71.634-160 160s71.634 160 160 160 160-71.634 160-160S296.366 48 208 48zM0 208C0 93.125 93.125 0 208 0s208 93.125 208 208c0 48.741-16.765 93.566-44.843 129.024l133.826 134.018c9.366 9.379 9.355 24.575-.025 33.941-9.379 9.366-24.575 9.355-33.941-.025L337.238 370.987C301.747 399.167 256.839 416 208 416 93.125 416 0 322.875 0 208z">
</path>
</svg></span></button>
</div>
</form>
Text Content
Skip to content Menu Menu * Tutorials * Latex Tutorials * Python Programming * Django Tutorial * Flask Tutorial * Spring Boot Tutorial * Data Science Tutorials * Free Certification * Cheatsheets * Blogs * Internship * About Us Home » Cheatsheet » FastAPI Python Library CheatSheet FASTAPI PYTHON LIBRARY CHEATSHEET Last Updated: 30th December 2023 by Editorial Team FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use and efficient, making it a popular choice among developers for building robust and scalable APIs. To help you harness the power of FastAPI more effectively, here’s a cheatsheet that covers some of the essential concepts and features. INSTALLATION pip install fastapi CREATING A FASTAPI APPLICATION from fastapi import FastAPI app = FastAPI() DEFINE ENDPOINTS from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, query_param: str = None): return {"item_id": item_id, "query_param": query_param} Please enable JavaScript Video Player is loading. Play Video Play Unmute Current Time 0:00 / Duration 2:23 0:00 Remaining Time -2:23 1x Playback Rate Subtitles Auto(360pLQ) Fullscreen Settings * Settings * SubtitlesCaptions Off * Speed1x * Qualityauto * Back * subtitles off, selected * American English Captions * Back * 2x * 1.5x * 1x, selected * 0.5x * Back * 1080pFHD * 720pHD * Auto(360pLQ) Watch on Humix Introduction to FastAPI for Machine Learning Share Watch on REQUEST PARAMETERS QUERY PARAMETERS from fastapi import FastAPI app = FastAPI() @app.get("/items/") def read_item(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit} PATH PARAMETERS from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} REQUEST BODY from fastapi import FastAPI, Body app = FastAPI() @app.post("/items/") def create_item(item: dict = Body(...)): return {"item": item} QUERY PARAMETERS AND TYPES from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") def read_item(skip: int = Query(0, title="Skip", description="Number of items to skip")): return {"skip": skip} PATH PARAMETERS AND TYPES from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") def read_item(item_id: int = Path(..., title="Item ID", description="The ID of the item")): return {"item_id": item_id} REQUEST BODY AND TYPES from fastapi import FastAPI, Body app = FastAPI() class Item: name: str description: str = None price: float tax: float = None @app.post("/items/") def create_item(item: Item): return {"item": item} REQUEST HEADERS from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") def read_item(api_key: str = Header(..., convert_underscores=False)): return {"api_key": api_key} DEPENDENCY INJECTION from fastapi import FastAPI, Depends app = FastAPI() async def get_db(): db = DBSession() try: yield db finally: db.close() @app.get("/items/") async def read_items(db: Session = Depends(get_db)): return db.query(Item).all() OAUTH2 AUTHENTICATION from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.get("/items/") def read_items(token: str = Depends(oauth2_scheme)): return {"token": token} MIDDLEWARE from fastapi import FastAPI, Request app = FastAPI() async def simple_middleware(request: Request, call_next): print("Middleware Before Request") response = await call_next(request) print("Middleware After Request") return response app.middleware(simple_middleware) @app.get("/") def read_root(): return {"Hello": "World"} This cheatsheet covers some of the key features and concepts of FastAPI. For more detailed information, refer to the official documentation. Use this cheatsheet as a quick reference guide to accelerate your development process with FastAPI. FAQ 1. WHAT IS FASTAPI, AND HOW DOES IT DIFFER FROM OTHER WEB FRAMEWORKS? FastAPI is a modern, high-performance web framework for building APIs with Python. It stands out for its use of Python type hints to enable automatic data validation and documentation generation. Unlike traditional frameworks, FastAPI leverages the capabilities of Python 3.7+ to provide fast, efficient, and type-safe API development. 2. HOW DO I HANDLE AUTHENTICATION IN FASTAPI? FastAPI supports various authentication methods, including OAuth2, API keys, and others. For example, you can use OAuth2PasswordBearer for token-based authentication. By defining dependencies using the Depends function, you can easily integrate authentication into your route functions, ensuring secure access to your API endpoints. 3. CAN I USE FASTAPI WITH AN ASYNCHRONOUS DATABASE? Yes, FastAPI is built with asynchronous programming in mind, and it works seamlessly with asynchronous databases. You can use tools like SQLAlchemy with an asynchronous driver (such as databases or databases[asyncpg]) to perform asynchronous database operations. This allows you to take full advantage of the performance benefits of asynchronous programming. 4. HOW CAN I HANDLE REQUEST VALIDATION AND SERIALIZATION IN FASTAPI? FastAPI utilizes Python type hints for automatic request validation and serialization. By declaring the types of your function parameters or request bodies, FastAPI will automatically validate incoming requests and generate detailed API documentation. This feature not only enhances code readability but also ensures that your API inputs are correctly formatted. 5. DOES FASTAPI SUPPORT MIDDLEWARE FOR ADDITIONAL PROCESSING? Yes, FastAPI supports middleware, allowing you to perform additional processing before and after handling requests. Middleware functions are defined using asynchronous request-response patterns, enabling tasks such as logging, authentication checks, or modifying the request/response cycle. This flexibility makes it easy to integrate custom logic into your FastAPI application. Categories Cheatsheet OpenCV Python Library Cheatsheet Pytest Python Library Cheatsheet CATEGORIES * 5g * Blog * Cheatsheet * computer networks * computer organization * Data Science & Machine Learning * dbms * Django Tutorial * docker tutorial * Flask * free hosting * Git Tutorial * Latex * operating system * Python Programming * ReactJs * Spring Boot * theory of computation Search RELATED POSTS * PHP Programming Language Cheatsheet * Firebase Realtime Database Cheatsheet * InfluxDB Database Cheatsheet * Python OOPS CheatSheet * Requests Python Library Cheatsheet * Rust Programming Language Cheatsheet * Flow Programming Language Cheatsheet * Oracle Database Cheatsheet * Matlab Programming Language Cheatsheet * C++ Programming Language Cheatsheet More Cheatsheet Tutorials 〉〉 © 2024 StudyGyaan • All Rights Reserved! Search for: Go to mobile version 🌎 ✕ 🍪 PRIVACY & TRANSPARENCY We and our partners use cookies to Store and/or access information on a device. We and our partners use data for Personalised advertising and content, advertising and content measurement, audience research and services development . An example of data being processed may be a unique identifier stored in a cookie. Some of our partners may process your data as a part of their legitimate business interest without asking for consent. To view the purposes they believe they have legitimate interest for, or to object to this data processing use the vendor list link below. The consent submitted will only be used for data processing originating from this website. If you would like to change your settings or withdraw consent at any time, the link to do so is in our privacy policy accessible from our home page.. Manage Settings Continue with Recommended Cookies Vendor List | Privacy Policy