This article provides a detailed guide to What Is FastAPI in Python? It covers how FastAPI works, its key features and limitations, and the steps to build and test your first Python REST API.
Have you ever wondered how a website or mobile app sends information to a Python programme and receives a response it can use?
Imagine you manage stock for a business with three branches. Your billing system needs to record new products, your website needs to display prices, and your staff need to check availability from their phones. You already have the stock data in Python, but each application needs a consistent way to request it. Your backend also needs to reject mistakes such as a negative selling price or a missing product name.
Building this connection is one practical use of FastAPI. It is an open-source Python web framework that helps you create API endpoints, validate incoming data, and generate interactive documentation. A developer can use that documentation to try a request and see how your API responds.
However, a working endpoint is only one part of a reliable backend. You also need to decide who can access each record, where the data will be stored, and what happens when a request fails or gets sent twice. These decisions matter when several branches, apps, or customers depend on the same API.
Whether you are learning Python, developing a mobile app, running a SaaS business, or bringing an AI model into a customer-facing product, understanding FastAPI can help you decide how to connect your Python code to the applications that need it.

In this Oflox® guide, we will explore how FastAPI handles requests, explain how it differs from Flask and Django REST Framework, and show you how to build, test, and prepare an inventory API for production.
Let’s explore it together!
Table of Contents
What Is FastAPI in Python?
FastAPI is an open-source Python web framework for building APIs. It uses Python type hints and Pydantic models to validate requests, define responses, and generate OpenAPI documentation. It supports synchronous and asynchronous route functions. You can use Swagger UI to try its endpoints in a browser.
An API, or application programming interface, gives one piece of software a defined way to ask another for data or work. For example, a mobile app can send GET /products/1 to retrieve product 1. A billing application can send POST /products with a JSON body to create a product.
An endpoint is a specific operation a client can call. The HTTP method matters. GET /products can list products, while POST /products can create one. Both use the same path and have different responsibilities.
The usual spelling is FastAPI, as one word. “Fast API in Python” is a common way of searching for the framework.
FastAPI at a Glance:
| Item | Explanation |
|---|---|
| What it is | An open-source Python web framework for building APIs |
| Common uses | Web and mobile backends, internal services, integrations, and AI model endpoints |
| Web foundation | Starlette |
| Data modelling and validation | Pydantic |
| Interface between application and server | ASGI |
| Common server | Uvicorn |
| API description | OpenAPI, available by default at /openapi.json |
| Browser documentation | Swagger UI at /docs and ReDoc at /redoc by default |
| Route styles | Regular def and asynchronous async def |
| Database | Optional and chosen by the developer |
Why Is FastAPI Important?
API development involves more than writing functions. Both sides need to agree on what a request contains, what a successful response looks like, and what happens when a request fails. That agreement is the API contract.
- It makes input rules easier to find. A price field can declare that it accepts a positive integer. A list endpoint can declare that it returns at most 50 items per request. Defined close to the endpoint, these rules are easier to review and can appear in the generated API description.
- It helps frontend and backend developers work together. A frontend developer can use Swagger UI to try a request before their screen is ready. If a field is unclear, both developers can inspect the actual response and agree on its meaning before releasing the app.
- It helps protect client compatibility. Suppose your app reads price_paise and divides it by 100 to display rupees. Renaming the field to price can break an installed mobile app even after the website has been updated. A documented response gives your team a reference when reviewing such changes.
- It works well with Python-based services. A team that already has a Python reporting script or prediction model can write an HTTP interface around it. A dashboard built in another language can then send requests to the Python service and use the results.
History and Background of FastAPI
Sebastián Ramírez created FastAPI. The Python Package Index records the release of version 0.1.0 on 8 December 2018. The project’s design notes explain how earlier web frameworks, validation libraries, and API standards influenced its development.
One useful design choice was to build around Python type hints. In a function argument, product_id: int tells a developer and their editor that the value should be an integer. FastAPI can also use that declaration to interpret a value received in an HTTP request.
Two packages provide much of the foundation. Starlette supplies web capabilities such as routing and WebSockets. Pydantic supplies data models and validation. To serve the application, you run it with an ASGI server such as Uvicorn. ASGI stands for Asynchronous Server Gateway Interface and defines how the server and the application communicate.
How Does FastAPI Work?
Consider an application that sends GET /products/12. Here is what happens from the request to the response.
1. The Server Receives the Request
An ASGI server such as Uvicorn receives the incoming connection and passes request information to the FastAPI application. FastAPI uses the HTTP method and URL path to find the matching route.
2. FastAPI Reads the Input
The framework extracts the values the route expects. In /products/12, 12 is a path parameter. In /products?limit=5, limit is a query parameter. A request can also include a JSON body, headers, or cookies.
3. The Framework Validates the Data
If the route expects a positive integer, 12 passes and 0 fails. If a request body requires a product name and price, FastAPI uses the declared model to check the submitted fields. A failed request validation commonly returns HTTP 422, with details about the issue.
4. The Python Function Applies Business Rules
After validation, the route function can fetch the product, check access, or call another service. A correctly formatted product ID can still refer to a missing record. In that case, the function can return HTTP 404. A valid ID that belongs to another branch also needs an access check.
5. FastAPI Prepares the Response
When you declare a response model, FastAPI uses it to validate, serialise, and filter the outgoing data. For example, a product record may contain the supplier’s cost price, while the public response exposes only the product name and selling price. The declared response structure can also appear in the OpenAPI document.
Who Should Use FastAPI?
Start with the problem your application needs to solve. The same framework can support a beginner project and a production service, but the work surrounding the API will differ.
| Project situation | How FastAPI can help | What to plan for |
|---|---|---|
| Learning Python backend development | Build routes, inspect JSON, and practise validation | Start with one GET and one POST endpoint |
| Building a mobile or React backend | Give clients a documented HTTP interface | Plan authentication, error handling, and browser CORS where applicable |
| Connecting billing and inventory | Accept structured updates and expose current records | Add transactions, permissions, and duplicate submission handling |
| Serving a Python AI model | Define input and output models for predictions | Measure response time, memory use, and processing cost |
| Receiving payment or delivery webhooks | Accept event notifications at a dedicated endpoint | Verify provider signatures and handle repeated events |
| Extending an existing Django product | Add a separate Python service when it has a clear purpose | Weigh separate hosting and monitoring against reusing the existing Django app |
FastAPI vs Flask vs Django REST Framework
All three can return JSON and power production applications. The practical choice depends on what your team already uses and how much functionality the project needs.
| Framework | Consider it when | What your team needs to decide |
|---|---|---|
| FastAPI | The API contract is central to the product, or the service often calls asynchronous dependencies | Which database, permissions, and admin tools fit the project |
| Flask | You need a lightweight framework with a flexible structure, or you already use Flask | Which packages will handle validation and OpenAPI documentation |
| Django REST Framework | The API works with an existing Django project or needs Django’s ORM, authentication, or admin | How the public API should map to your existing data and permissions |
Flask supports async views with its async extra. Under its standard WSGI model, each request still occupies a worker for its duration. Django REST Framework builds on Django. If a back-office team needs to manage products, users, and suppliers through an admin interface from the first release, include that requirement when comparing frameworks.
How to Build Your First FastAPI Application
Here’s how to build your first FastAPI application, step by step. You’ll set up a Python project, create a simple inventory API, and test it with valid and invalid requests.
1. Create a Project and Virtual Environment
Open a terminal and run these commands.
mkdir inventory-api
cd inventory-api
python -m venv .venv
Activate the environment using the command for your operating system.
- Windows PowerShell — ..venv\Scripts\Activate.ps1
- macOS or Linux — source .venv/bin/activate
Then install FastAPI with its standard dependencies. If your machine uses python3 or py -3, use that command when creating the environment.
python -m pip install "fastapi[standard]"
2. Create the Models and Routes
Create a file named main.py. The ProductCreate model defines what clients send. ProductPublic includes the ID that clients receive.
from typing import Annotated
from fastapi import FastAPI, HTTPException, Path, Query, status
from pydantic import BaseModel, Field
app = FastAPI(title="Inventory API", version="1.0.0")
class ProductCreate(BaseModel):
name: str = Field(min_length=1, max_length=80)
price_paise: int = Field(gt=0, strict=True)
in_stock: bool = True
class ProductPublic(ProductCreate):
id: int
products = {
1: ProductPublic(
id=1, name="Notebook", price_paise=4999, in_stock=True
)
}
@app.get("/products", response_model=list[ProductPublic])
def list_products(limit: Annotated[int, Query(ge=1, le=50)] = 10):
return list(products.values())[:limit]
@app.get("/products/{product_id}", response_model=ProductPublic)
def get_product(product_id: Annotated[int, Path(ge=1)]):
product = products.get(product_id)
if product is None:
raise HTTPException(status_code=404, detail="Product not found")
return product
@app.post(
"/products",
response_model=ProductPublic,
status_code=status.HTTP_201_CREATED,
)
def create_product(payload: ProductCreate):
product = ProductPublic(id=max(products, default=0) + 1, **payload.model_dump())
products[product.id] = product
return product
Here is what the declarations do.
- Field(gt=0) requires a price greater than zero.
- strict=True requires a JSON integer such as 7500. A quoted value such as “7500” fails validation.
- Path(ge=1) requires a product ID of at least one.
- Query(ge=1, le=50) allows list limits from one to 50. The default is 10.
- response_model=ProductPublic declares which fields a single-product response contains.
- status_code=status.HTTP_201_CREATED sets the successful creation response to HTTP 201.
The sample stores its records in a Python dictionary. Restarting the application resets the data, each worker has its own copy, and two simultaneous writes can calculate the same ID. In a production project, let the database assign IDs and enforce uniqueness. Use transactions for changes that must succeed together.
3. Start the Server and Open Swagger UI
Run this command in the folder containing main.py.
fastapi dev main.py
Open http://127.0.0.1:8000/docs. Expand a route, click Try it out, and execute the request. You can also open /redoc for a reference view or /openapi.json for the machine-readable contract.
4. Send Valid and Invalid Requests
In a Bash-compatible terminal, call the routes with curl. You can also send the same requests from Swagger UI.
curl -i http://127.0.0.1:8000/products/1
curl -i http://127.0.0.1:8000/products \
-H 'Content-Type: application/json' \
-d '{"name":"Desk Calendar","price_paise":7500}'
The first request returns HTTP 200 with the notebook. The second returns HTTP 201 with the new product. Its response includes “in_stock”: true because the request omitted that field.
| Request to try | Expected result | What it shows |
|---|---|---|
| GET /products/1 | 200 OK | An existing product can be retrieved |
| GET /products/99 | 404 Not Found | The ID is valid, but the product is absent from the sample |
| GET /products/0 | 422 | The path value failed validation |
| GET /products?limit=100 | 422 | A query value exceeded its defined range |
| POST /products with price 7500 | 201 Created | The request passed and created a record |
| POST /products with price -7500 | 422 | The price failed the body constraint |
5. Add Automated Tests
Create test_main.py next to main.py. The test client calls the application directly. Each test starts with the same inventory so it can run independently.
import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
from main import app, products
class InventoryAPITests(unittest.TestCase):
def setUp(self):
self.enterContext(patch("main.products", {1: products[1]}))
self.client = self.enterContext(TestClient(app))
def test_create_product(self):
result = self.client.post(
"/products", json={"name": "Desk Calendar", "price_paise": 7500}
)
self.assertEqual(result.status_code, 201)
self.assertEqual(result.json(), {
"id": 2,
"name": "Desk Calendar",
"price_paise": 7500,
"in_stock": True,
})
def test_reject_invalid_price(self):
result = self.client.post(
"/products", json={"name": "Desk Calendar", "price_paise": -7500}
)
self.assertEqual(result.status_code, 422)
self.assertEqual(result.json()["detail"][0]["loc"], ["body", "price_paise"])
def test_product_missing(self):
self.assertEqual(self.client.get("/products/99").status_code, 404)
def test_invalid_path_and_query(self):
self.assertEqual(self.client.get("/products/0").status_code, 422)
self.assertEqual(self.client.get("/products?limit=100").status_code, 422)
Run the test suite.
python -m unittest -v
All four tests passed when run against this example. Once you add a real database, test that a newly created product can be read back. If you add branch permissions, also test that a user from one branch cannot read a product from another branch even if they know its ID.
Practical Example — PG Hisaab and a Room Availability API
Consider PG Hisaab, a PG management software brand. Suppose a PG owner manages two properties and wants to see which rooms have available beds. A dashboard needs current availability, while an authorised manager needs to assign a bed to a tenant.
A hypothetical API could support these operations:
| Endpoint | What it could do | Business rule to consider |
|---|---|---|
| GET /properties/7/rooms | List rooms for property 7 | Return data only to users authorised for that property |
| GET /rooms/12/availability | Show available beds in room 12 | Avoid including private tenant details in the availability response |
| POST /bed-assignments | Assign a bed to a tenant | Prevent two managers from assigning the same bed at once |
| GET /tenants/25/receipts | Retrieve receipts for a tenant | Check that the caller can access the tenant’s property and payment records |
FastAPI can check that the bed ID and tenant ID have the expected format. The application still has to verify that both belong to the correct property and that the caller has permission. A database transaction and appropriate constraints can protect the assignment when two people act at the same time.
This is an illustrative design for a PG management product. The endpoints describe how such an API could work.
Key Features and Benefits of FastAPI
Here are the key features of FastAPI and how they help you validate requests, document endpoints, and reuse logic across your application.
- Automatic API documentation: FastAPI generates an OpenAPI description from the operations and models you define. Swagger UI lets developers try requests, while ReDoc provides a reference view. Add descriptions for behaviours that the schema cannot express, such as when a report will become available or how a client should retry.
- Reusable dependencies: Depends lets you declare that a route needs a value or check before it runs. A set of routes can share the same user lookup or database session logic. Tests can then focus on the behaviour of each endpoint and the conditions under which access should be granted.
- Separate input and output models: A client may send information that should never be returned. A registration form, for example, may accept a password, while the public response returns the user’s ID and display name. Declare what the caller can receive and test those fields.
- Support for synchronous and asynchronous code: Use async def when the libraries you call offer awaitable operations. While an async network request is waiting, the event loop can handle other requests. A normal
defroute can be a good fit for a blocking database driver or SDK. FastAPI runs those route functions in a thread pool. - WebSockets and streaming: A live dashboard can use a WebSocket to receive updates over a persistent connection. Streaming can suit a response that arrives in stages. In either case, decide how the client reconnects or recovers when the connection drops.
Limitations and Common Challenges
Here are some common challenges you may face when using FastAPI, from choosing when to use async code to handling long-running tasks and deploying your API.
- Async Code Needs Compatible Libraries: Adding async def to a route does not make a blocking SDK asynchronous. A regular helper called directly from an async route can still block the event loop. Check what your client libraries do before choosing the route style.
- Heavy Jobs Need a Different Execution Plan: Generating a large report or running a CPU-intensive model can tie up a request for longer than the client is willing to wait. For a job that needs retries or must survive restarts, record it in a durable job store, process it with a worker, and let the client check its status.
- Production Requires Operational Work: Plan HTTPS, health checks, restart behaviour, and dependency upgrades. If you run multiple workers, account for memory and database connections. Four workers with a database connection pool of ten each can use up to forty connections before overflow or additional replicas. Check this against the database limit before changing worker counts.
- Validation Covers Only Part of the Request: A valid phone number, tenant ID, or stock quantity tells you the input matches a rule. Your application still needs to decide whether the caller may access a particular record and whether the operation is allowed in its current state. Test those decisions as well as the field constraints.
- Performance Depends on the Whole Request: A simple endpoint can respond quickly while a report remains slow because of a database query or external provider. Load test with realistic data. Track response time, error rate, CPU, and memory. Check p95 latency, the time within which roughly 95 per cent of requests finish, alongside the median so slower requests are visible.
5+ Helpful FastAPI Tools and Resources
Here are some helpful tools and resources for building, testing, documenting, and deploying FastAPI applications.
| Tool or resource | Useful for |
|---|---|
| Swagger UI | Trying endpoints directly from a browser |
| curl or Postman | Sending requests with custom headers, bodies, and parameters |
| Uvicorn | Running the ASGI application |
| PostgreSQL | Storing shared records and enforcing database constraints |
| SQLAlchemy and Alembic | Database access and schema migrations |
| FastAPI TestClient with unittest or pytest | Checking responses, validation errors, and access rules |
| Docker | Packaging the application and its dependencies |
| Celery or a managed queue | Running jobs that need independent processing or retries |
| OpenTelemetry | Tracing requests through the application and its dependencies |
Choose tools based on the problem you can see. A small internal API can begin with one service, one database, and a few integration tests. If several clients depend on the API, checking OpenAPI changes before release may have more immediate value than introducing more services.
Expert Tips and Common Mistakes
Here’s how to build a more reliable FastAPI application and avoid common mistakes when validating requests, handling errors, and preparing your API for production.
1. Expert Tips
- Document a real request and response. A price field called price_paise is easier to understand when the example shows that 7500 represents ₹75.
- Test one complete customer journey. For an order workflow, create an order, confirm access, retry the submission, and inspect the final records.
- Set timeouts on external calls. If a courier provider stops responding, decide how long to wait and what the caller should receive.
- Plan database migrations before release. If old and new app versions run together, introduce compatible changes first and enforce new constraints once the rollout is ready.
- Test what fails as well as what works. Check invalid input, missing records, unauthorised access, and repeated requests.
2. Common Mistakes
| Mistake | Better approach |
|---|---|
| Returning a database record as-is | Define a public response model and test the fields it exposes |
| Treating generated documentation as complete | Explain side effects, error meanings, and retry rules |
| Keeping production records in an in-memory dictionary | Store shared and persistent records in a database |
| Processing the same webhook twice | Record the provider’s event ID and enforce uniqueness |
| Doing long-running work during a request | Use a worker and return a job ID where appropriate |
| Increasing workers without checking capacity | Measure memory and database connections under realistic traffic |
| Assuming a framework benchmark predicts product performance | Run a benchmark that reflects actual client requests |
FAQs:)
A. FastAPI is an open-source Python web framework for building APIs. It uses type hints and Pydantic models to validate requests, define responses, and generate OpenAPI documentation.
A. Sebastián Ramírez created FastAPI. PyPI records the release of version 0.1.0 on 8 December 2018.
A. Yes. If you understand functions, dictionaries, and simple Python type hints, start with one GET route and add a POST route with a Pydantic model.
A. FastAPI defines your routes and application behaviour. Uvicorn is an ASGI server that accepts connections and runs the application.
A. No. It can return calculated values, call an external service, or keep temporary data in memory. Add a database when records must persist or be shared across processes.
A. The request commonly failed validation. Check the detail entries and their loc values to find the field in the body, query, or path that caused the error.
A. Yes. Both can call a FastAPI endpoint over HTTP. Plan the JSON contract and authentication, and configure CORS for a browser frontend hosted on a different origin.
A. No. FastAPI supports ordinary def routes. Use async def when the underlying libraries have awaitable operations and the workload benefits from concurrency.
A. Performance depends on the operation, database, external calls, and deployment. Compare the same workload under equivalent conditions before deciding.
A. Yes. You can expose a Python model through an API. Choose direct responses, streaming, or background jobs based on model runtime, memory use, and how the client receives the result.
Conclusion:)
Understanding what FastAPI is in Python helps you turn Python code into an API that websites, mobile apps, and other software can use through a clear, documented interface.
Start with one practical task. Build a route, define the data it accepts, and test what happens when the request succeeds or fails. Before taking the API live, check that it protects private records, stores data reliably, and handles repeated requests without creating duplicate entries.
At Oflox®, we approach custom software and AI development by defining what each client needs from the API, which records it can access, and how it should recover when a request fails. Those decisions guide the backend design from the first endpoint.
“A dependable API makes it clear what to send, what to expect, and what to do when a request fails.” — Suggested quote for Mr Rahman, Oflox®
Read also:)
- What Is a DUNS Number? A-to-Z Guide for Beginners!
- What Is PG Management Software? A Complete Guide!
- What Is a Content Hub? A-to-Z Guide for Beginners!
Have you built an API with FastAPI? Share what it does and the biggest challenge you faced while building or deploying it in the comments below.