What is FastAPI in simple words? Starting a server, GET example, WebSockets and auth

FastAPI and APIs in simple words, starting a project and server, a GET example, WebSockets and WebSocket authentication, FastAPI vs Flask, and AI agents simply.

Presenting to a room
Presenting to a room

Key takeaways

  • FastAPI is a Python tool for building web APIs quickly, with automatic checks on incoming data and free documentation.
  • An API lets programs talk to each other; FastAPI helps you build one.
  • Start with pip install fastapi[standard], write an app, and run fastapi dev main.py.
  • FastAPI supports WebSockets; authenticate them with a token in the query, cookie or first message, checked before accepting.
  • An AI agent is software that uses an AI model to decide steps and take actions towards a goal.

In simple words, FastAPI is a Python framework that lets you build web APIs, the back-end services apps talk to, quickly and safely: you write normal Python functions with type hints, and FastAPI turns them into web endpoints, checks incoming data, and creates interactive documentation automatically. It is popular for AI services because Python is the language of AI. FastAPI powers back ends in my products, including FaceVision, so this page explains FastAPI and APIs simply, starting a server, a GET example, WebSockets and their authentication, choosing between FastAPI and Flask, and AI agents simply.

What is FastAPI in simple words?

FastAPI is a tool for building the part of an app that runs on a server and answers requests. You write Python functions, mark them with a route like /users, and FastAPI makes them available over the internet, checking that incoming data is correct.

Imagine a restaurant: the front end is the menu customers see, and the API is the kitchen taking orders and sending dishes back. FastAPI helps you build the kitchen with clear rules about what orders look like. It is fast to write, fast to run, and generates a web page at /docs where you can test every endpoint without extra tools.

What is an API, and what is FastAPI?

An API, application programming interface, is a set of rules that lets one program request data or actions from another, for example a mobile app asking a server for your order history. Web APIs usually exchange JSON over HTTP.

Also asked as: what is api and fastapi · can i do websocket in fastapi · how i solved websocket authentication in fastapi (and why depends() wasn't enough

FastAPI is a framework for building web APIs in Python. You define endpoints, the URLs and methods such as GET and POST, and the data they accept and return; FastAPI handles routing, validation, conversion to JSON and documentation. Other frameworks include Flask and Django in Python, and Express in JavaScript. FastAPI stands out for type-hint-based validation and automatic docs.

How do I start with FastAPI?

Install Python, create a virtual environment, install FastAPI, write a small app in main.py, and run it with the FastAPI command. Then open the automatic documentation in your browser to test it.

Also asked as: how to start fastapi

Steps:

  • python -m venv .venv and activate it.
  • pip install "fastapi[standard]".
  • Create main.py with app = FastAPI() and one route.
  • Run fastapi dev main.py.
  • Open http://127.0.0.1:8000/docs.

Next, follow the official tutorial: path and query parameters, request bodies with Pydantic, dependencies, databases and testing. Build a small project, such as a notes API, as you learn. Writing tests with FastAPI's TestClient from the start makes later changes much safer.

How do I start a FastAPI server?

For development, run fastapi dev main.py, which starts a server with automatic reload on code changes. For production, run fastapi run main.py or Uvicorn directly, such as uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4.

Also asked as: how to start fastapi server

On hosting platforms, set the start command to bind to the platform's port, often from a PORT environment variable. Use multiple workers or a process manager for production traffic, and put a reverse proxy in front for HTTPS. If the server does not start, check for import errors, a port already in use, or a wrong module path in the command.

What is a FastAPI GET example?

A GET endpoint returns data. This example returns a greeting and accepts an optional query parameter:

from fastapi import FastAPI
app = FastAPI()

@app.get("/greet/{name}")
def greet(name: str, lang: str = "en"):
    message = "Namaste" if lang == "hi" else "Hello"
    return {"message": f"{message}, {name}"}

Visiting /greet/Asha?lang=hi returns {"message": "Namaste, Asha"}. FastAPI validates that name and lang are strings and documents both in /docs. Add response models to control output, and use path parameters for identifiers and query parameters for options and filters.

Can I use WebSockets in FastAPI?

Yes. FastAPI supports WebSockets for real-time, two-way communication, such as chat, live dashboards, notifications and streaming progress. Define an endpoint with @app.websocket, accept the connection, then send and receive messages in a loop.

from fastapi import WebSocket
@app.websocket("/ws")
async def ws(websocket: WebSocket):
    await websocket.accept()
    while True:
        text = await websocket.receive_text()
        await websocket.send_text(f"echo: {text}")

Handle disconnects with WebSocketDisconnect, and use a connection manager for broadcasting. FineTune Studio streams live training loss to the browser this way. For multiple server instances, share messages through Redis pub/sub or a similar broker, since each process only knows its own connections. For one-way streaming, such as AI responses, server-sent events or streaming HTTP responses are often simpler than WebSockets.

How do I authenticate WebSockets in FastAPI?

Browsers cannot set custom headers such as Authorization when opening a WebSocket, so header-based dependencies like HTTPBearer often fail. Instead, pass a token in a query parameter, a cookie, or the first message, validate it before accepting, and close the connection with a policy-violation code if invalid.

Dependencies with Depends() do work on WebSocket endpoints, but they must read from sources the WebSocket provides, such as Query or Cookie, and raise WebSocketException rather than HTTPException. Prefer short-lived tokens, since query strings may appear in logs, or issue a one-time ticket from an authenticated HTTP endpoint. Always use secure WebSockets, wss://, in production.

When should I choose FastAPI?

Choose FastAPI for API-first back ends, especially when you want automatic validation and documentation, async I/O for calling external services, streaming responses, or Python-based AI and machine learning features.

Also asked as: when to choose fastapi

It fits mobile app back ends, microservices, AI inference and RAG services, internal tools' APIs and webhook receivers. Its type hints make large codebases easier to maintain, and the generated OpenAPI schema helps front-end teams. For full websites with server-rendered pages and an admin panel, Django may be more complete; for tiny scripts, Flask or FastAPI both work.

Why choose Flask over FastAPI?

Choose Flask when you want maximum simplicity for small synchronous apps, rely on Flask's mature extension ecosystem, maintain existing Flask code, or build server-rendered pages with Jinja templates where API validation and async matter less.

Flask has a huge body of tutorials, extensions for authentication, admin and forms, and a gentle learning curve. FastAPI has advantages for modern APIs, but Flask remains perfectly capable for many projects. Team familiarity matters: a team experienced in Flask may deliver faster with it. For new AI-heavy APIs, FastAPI is usually the stronger default.

What is an AI agent in simple words?

An AI agent is a program that uses an AI model to work towards a goal by deciding steps and taking actions with tools, such as searching the web, reading files or updating a system, rather than only answering a question.

Also asked as: what is ai agent in simple words

For example, asking an agent to "find three laptops under my budget and make a comparison table" leads it to search, read product pages, compare specifications and build the table. Agents need limits and supervision because they can make mistakes. Many AI agents run on back ends built with frameworks like FastAPI, which expose their tools as API endpoints.

Sources

  1. FastAPI, documentationfastapi.tiangolo.com
  2. FastAPI, First stepsfastapi.tiangolo.com
  3. FastAPI, WebSocketsfastapi.tiangolo.com
  4. MDN Web Docs, WebSocket APIdeveloper.mozilla.org
  5. Flask, documentationflask.palletsprojects.com
Pranjul Rathour
Pranjul Rathour
GenAI Engineer · India

GenAI engineer and AI product builder with 2+ years shipping production-grade AI systems: RAG pipelines, fine-tuned LLMs, hybrid retrieval and multi-modal apps across vision, speech and OCR, architected end to end from ingestion to deployment. Leads engineering for SCULT INDIA's 14-member team, founded the 500+ member TechVerse Enclave community and has mentored 200+ students. Three hackathon first prizes: Changethon 2025 (IIT Roorkee), Product Genesis at Vividhotsava 2025 (CSJMU) and BYTEBATTLE (MeetKats).

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way. Email pranjulrathour41@gmail.com.

Keep reading

More on Shipping AI apps

All Shipping AI apps guides →
Campus talks · hackathon judging · mentoring

Want this as a live session at your college?

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way.

Pranjul Rathour, GenAI engineer in India