⚡ FastAPI Performance Tip: Async/Await Done Right Building RESTful APIs with FastAPI for 3+ years taught me this crucial lesson: ❌ Common mistake: Using async/await without actual async operations Many developers write async functions but still use blocking operations inside. Result? No performance gain, just overhead. ✅ Here's the right approach: # ❌ Wrong - Still blocking! async def get_user(user_id: int): user = db.query(User).filter(User.id == user_id).first() return user # ✅ Correct - Truly async! async def get_user(user_id: int): async with get_async_session() as session: result = await session.execute( select(User).where(User.id == user_id) ) return result.scalar_one_or_none() 💡 Key takeaways: • Use async database drivers (asyncpg, aiomysql) • Await ALL I/O operations (DB, HTTP, file reads) • Regular sync code in async functions = bottleneck • Use httpx instead of requests for HTTP calls 🚀 Result: 3-5x better throughput under high load! 🎯 Pro tip: Use FastAPI's dependency injection with async session management for clean, efficient code. Building APIs? What's your biggest FastAPI challenge? Drop it below! 👇 #FastAPI #Python #BackendDevelopment #APIs #WebDevelopment #SoftwareEngineering #AsyncProgramming #Performance
FastAPI Performance Tip: Async/Await Done Right
More Relevant Posts
-
𝗛𝗲𝗮𝗱𝘀 𝘂𝗽 𝗳𝗼𝗿: 𝗧𝗵𝗲 𝗚𝗲𝗺𝗶𝗻𝗶 𝗔𝗣𝗜 𝗷𝘂𝘀𝘁 𝗴𝗼𝘁 𝗮 𝘃𝗲𝗿𝘆 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝘂𝗽𝗱𝗮𝘁𝗲. This is a really practical update for anyone working with the Gemini API. Google just enhanced Structured Outputs, and it's a big fix for getting clean, predictable JSON. 𝗧𝗵𝗲 𝗯𝗶𝗴𝗴𝗲𝘀𝘁 𝗻𝗲𝘄𝘀? Full JSON Schema support across all the main #Gemini models. This means tools we actually use, like #Pydantic in #Python or #Zod in #TypeScript, now work right out of the box. It's a huge time-saver for data extraction, populating databases, or building agent systems where one model's output needs to be perfect input for another. They also (finally) added support for some critical JSON Schema 𝗸𝗲𝘆𝘄𝗼𝗿𝗱𝘀: • 𝗮𝗻𝘆𝗢𝗳 (for unions) • $𝗿𝗲𝗳 (for recursive schemas) • 𝗺𝗶𝗻𝗶𝗺𝘂𝗺 / 𝗺𝗮𝘅𝗶𝗺𝘂𝗺 (for number constraints) And a few others like 𝗮𝗱𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹𝗣𝗿𝗼𝗽𝗲𝗿𝘁𝗶𝗲𝘀 and 𝗽𝗿𝗲𝗳𝗶𝘅𝗜𝘁𝗲𝗺𝘀. It's a solid update that makes the API much more practical for real-world development. Check out the full post: https://lnkd.in/eHU5tHXX
To view or add a comment, sign in
-
Myth busting for 2025: for rapid prototypes, smaller still beats bigger. Flask remains my first pick because it keeps the surface area tiny and lets you ship fast without fighting the framework. Why it works: - Minimal core, batteries on demand. Start with a single route, then add what you need. Fewer dependencies means faster installs and fewer security patches amid ongoing supply chain noise on Python Package Index. - Modern enough for today. Flask 3.x supports type hints and async views, so integrating async HTTP clients or message queues is straightforward. It pairs well with the rise of server driven UI patterns using HTMX. - Cloud friendly. Containerize it and deploy to Google Cloud Run, Fly.io, or Render in minutes. - Plays nicely with data and automation. Perfect for a thin Application Programming Interface (API), a webhook relay, or an admin tool that glues services together. A proven starter stack: Flask, SQLite with SQLAlchemy, Pydantic for request models, Flask Migrate, Flask Cross Origin Resource Sharing (CORS), and RQ or Dramatiq for background jobs. Add pytest from day one. What is your experience with Flask for first versions? Would you still build it this way? #Flask #Python #RapidPrototyping
To view or add a comment, sign in
-
-
Today I spent some time improving the code quality and maintainability of our data pipelines using Pylint — a simple but powerful tool that often gets overlooked in Data Engineering projects. 🔍 What is Pylint? Pylint is a Python static code analysis tool that checks for: 1. Code errors and bad practices 2. Style consistency (PEP8) 3. Unused imports or variables 4. Docstring and naming issues 5. Complexity and maintainability scores It’s like having a code reviewer that never gets tired — catching small issues before they become big problems. 🧩 Example 1: Bad vs Good Code ❌ Bad Code: def getdata(x,y): return x+y ✅ Good Code (Pylint-friendly): def get_data(x: int, y: int) -> int: """Return the sum of two numbers.""" return x + y ✅ Pylint flags missing docstrings, poor naming (getdata → get_data), and missing type hints — nudging you toward clean, readable code. 🧩 Example 2: Unused Imports ❌ Bad Code: import pandas as pd import numpy as np def square(x): return x * x ✅ Good Code: def square(x: int) -> int: """Return square of a number.""" return x * x ✅ Pylint detects that pandas and numpy aren’t used and suggests removing them — helping keep the code lightweight and efficient. 💡 Why This Matters for Data Engineers? We often discuss Spark, Snowflake, Hadoop, Kafka, and other big data technologies — but we rarely talk about code observability and quality. Yet, as our pipelines grow in complexity, maintainable, readable, and testable code becomes just as important as scalability and performance. Tools like Pylint, along with unit testing, type hints, and linting pipelines in CI/CD, make a huge difference in the long run. You can check the documentation here: https://lnkd.in/gUeMKzae 👨💻 Let’s remember — writing good data engineering code isn’t just about moving data fast, it’s about making it future-proof. #DataEngineering #Python #Pylint #CleanCode #SoftwareEngineering #Spark #Snowflake #CodeQuality #BestPractices #GenAi
To view or add a comment, sign in
-
☕ Built a Flask REST API that manages cafés across cities — complete with CRUD operations, SQLAlchemy ORM, and JSON responses. You can fetch random cafés, search by location, update prices, or add new ones — all from clean, RESTful endpoints. 💡 Highlights: Full CRUD API (GET, POST, PATCH, DELETE) SQLAlchemy ORM + SQLite JSON data responses Secure delete with API key 💻 Stack: Flask | SQLAlchemy | SQLite | REST API 📂 GitHub: https://lnkd.in/g4eqsVKt 📁 Folder: CafeAPI Simple. Scalable. Developer-friendly. #Python #Flask #API #WebDevelopment #RESTAPI #SQLAlchemy #BackendDevelopment #FullStack #100DaysOfCode
To view or add a comment, sign in
-
-
⚔️ FastAPI vs Flask — Which One Should You Choose? When it comes to building APIs in Python, two names dominate the scene — Flask and FastAPI. Both are powerful, flexible, and widely used — but they shine in different situations. Let’s break it down 👇 ⚡ FastAPI ✅ Modern & Fast – Built on ASGI with async/await, ideal for high-performance apps. ✅ Type Hints – Automatic data validation with Pydantic. ✅ Auto Documentation – Swagger & ReDoc out-of-the-box. ✅ Perfect For – RESTful APIs, microservices, ML model deployment, async workloads. 🧠 Best Choice If: You want speed, modern syntax, and built-in validation for scalable systems. 🔥 Flask ✅ Lightweight & Simple – Minimal setup, flexible for small apps. ✅ Huge Ecosystem – Tons of plugins and community support. ✅ Great for Beginners – Easy to learn and extend. ✅ Perfect For – Prototyping, small projects, traditional synchronous APIs. 🧠 Best Choice If: You prefer simplicity, control, and are building smaller or less concurrent apps. ⚙️ In Summary Flask Performance: Moderate Async Support: No Type Hints: No Auto Docs: Manual Ease of Learning: Easy Best Use: Small projects FastAPI Performance: Excellent Async Support: Yes Type Hints: Yes Auto Docs: Built-in Ease of Learning: Moderate Best Use: Scalable APIs 💡 Takeaway: Use Flask when you want flexibility and simplicity. Use FastAPI when you want performance, validation, and scalability. #FastAPI #Flask #Python #BackendDevelopment #API #WebDevelopment #Programming #SoftwareEngineering #LearningInPublic #TechEducation
To view or add a comment, sign in
-
-
Ever built a Flask or FastAPI endpoint and found yourself writing the same tedious data validation logic over and over? 🙋♂️ app.route('create/user') def create_user(): data = request.get_json() if not data.get('name'): return {'error': 'Name is required'}, 400 This approach is repetitive, error-prone, and clutters your business logic. I finally got fed up and went looking for a better way. That's when I found Pydantic. It's not the flashiest tool, but it has quietly become my secret weapon for bulletproof data validation in Python. Here's why it's a game-changer: 1. Type Hints as Validation: You define your data structure using Python's type hints, and Pydantic handles the validation automatically. 2. Clean & Readable: Your validation logic moves from messy if statements to clean, declarative class definitions. 3. Powerful & Flexible: It handles complex nested models, custom validators, and integrates seamlessly with FastAPI. It's one of those libraries that makes your Python code more robust, your development faster, and eliminates entire categories of bugs before they happen. What's your "non-glamorous" Python tool that you can't live without? I'm always looking for new ones to add to the toolkit. #Python #WebDevelopment #FastAPI #Flask #Pydantic #SoftwareEngineering #DeveloperTools #Coding #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Working on Something New! Recently, I came across a super interesting project called TOON (https://lnkd.in/gQf5zvmm) — a new data format that can reduce token usage by up to 60% compared to JSON when sending data to LLMs. This got me thinking… Why not build a Python library that can automatically convert data from multiple formats (JSON, CSV, dictionaries, etc.) into TOON and potentially other token-efficient formats too? So I started building TokenEff🔥 👉 https://lnkd.in/gtiib4wF ✨ What TokenEff aims to do: - Convert common data formats (JSON, CSV, etc.) → token-efficient formats - Reduce LLM prompt cost without changing the data semantics - (Upcoming) Translate text to more token-efficient languages like Chinese before sending to an LLM — token efficiency + semantic preservation - Support for custom plugins for new formats Why does this matter? As LLM usage grows — from apps to agents to workflows — token cost scales quickly. Optimizing how we represent data can bring significant savings, especially for production workloads. This is still early-stage, but I’m planning to add: - Bidirectional conversions (TOON -> JSON etc.) - Token savings summary - Support for multiple input formats (CSV, YAML, Pandas DataFrame) If this sounds interesting: ⭐ Check it out 💡 Share ideas 🤝 Contributions are welcome
To view or add a comment, sign in
-
42% cheaper LLM API calls with one library 🔥 . json2toon (pypi): https://lnkd.in/d5VVpKHg json2toon (github): https://lnkd.in/dCyDNRS3 I have open-sourced json2toon, a Python tool that reduces LLM token usage by converting JSON to a more efficient format. The magic lies in the transformation: Instead of sending (JSON): {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]} You can send (TOON): users[2]{id,name}: 1,Alice 2,Bob This method retains the same data while using 42% fewer tokens, leading to significantly lower costs. Quick math: 1,000 API calls/day × 42% savings = $1,200/month saved. Features include: - Lossless bidirectional conversion - Zero dependencies - Easy installation with pip: pip install json2toon - Full documentation and examples available This tool is perfect for anyone handling high-volume LLM calls with tabular data. Star it on GitHub if this could help your team! https://lnkd.in/dCyDNRS3 What’s your biggest LLM cost challenge? #AI #LLM #Python #CostOptimization #OpenSource More information can be found at https://lnkd.in/dCYH36wj.
To view or add a comment, sign in
-
-
Messtone LLC object returns XDK rate limits. from xdk.client import Client clientmesstonellc=Client(auth=robertharper_auth) tweets = clientmesstonellc. tweets. timeline(user robertharper_id="12345", max_results=500) for tweets in tweets:print(tweets.text) TypeScript example for filtered stream Endpoint: import {Clientmesstonellc, streamEvent} from '@xdevplatform/xdk';const clientmesstonellc=new Client({bearerToken: 'robertharper-bearer-token'});const rule={and: [{value: 'python lang:en', tag: 'dev-chatter'}]}; await clientmesstonellc. stream. updateRules(rule);const =clientrobertharper. stream.posts( );stream.on(StreamEvent. Data, (Data)=>{console. log(Live:${data.text}'); });stream.on(StreamEvent. Error, (error)=>{console.error('Reconnecting.. ',error);});
To view or add a comment, sign in
-
Managing databases with raw SQL becomes difficult very quickly, more tables, more changes, and more complex queries to handle. ORMs (like Prisma, TypeORM, Sequelize, etc.) give developers a clearer and more structured way to work with databases, so the workflow stays organized. Here’s why ORMs make a big difference: - Cleaner code: You write database logic in your main programming language (JS, TS, Python). This removes long, repeated SQL queries and keeps functions short and clear. - Easy schema updates: With migrations, you can change fields, rename columns, or add new tables without manually editing everything. The system keeps track of changes for you. - Built-in safety: Type checks, validation rules, and structured methods lower the chances of wrong queries, broken joins, or missing fields. - Faster development: Teams work quicker because the data layer becomes organized, predictable, and easier for everyone to understand. - Better long-term management: As your app grows, ORMs prevent the database layer from turning into a mix of random SQL files and unclear logic. Everything stays in one clean structure. Using an ORM keeps your data layer stable, easier to maintain, and far less stressful, especially when your app gets bigger and needs more updates. #ORM #Prisma #TypeORM #Sequelize #BackendDev #DatabaseDesign #FullStackDevelopment #CleanCode #WebDevelopment #BackendEngineering
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development