Convert Figma logo to code with AI

encode logostarlette

The little ASGI framework that shines. 🌟

10,027
897
10,027
39

Top Related Projects

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

67,504

The Python micro framework for building web applications.

79,088

The Web framework for perfectionists with deadlines.

21,674

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

14,938

Asynchronous HTTP client/server framework for asyncio and Python

17,995

Accelerate your web app development | Build fast. Run fast.

Quick Overview

Starlette is a lightweight ASGI framework/toolkit for building high-performance asyncio services. It's designed to be easy to use, yet powerful enough for production environments. Starlette can be used as a complete framework or as a toolkit for building larger applications or frameworks.

Pros

  • Fast and lightweight, with excellent performance benchmarks
  • Built-in support for WebSocket, GraphQL, and server-sent events
  • Easy to learn and use, with a clean and intuitive API
  • Highly extensible and customizable

Cons

  • Relatively young project compared to more established frameworks
  • Smaller ecosystem and community compared to larger frameworks like Django or Flask
  • Limited built-in features, requiring additional libraries for some common tasks
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Basic "Hello, World!" application:
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"message": "Hello, World!"})

app = Starlette(debug=True, routes=[
    Route("/", homepage),
])
  1. WebSocket example:
from starlette.applications import Starlette
from starlette.websockets import WebSocket
from starlette.routing import WebSocketRoute

async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message received: {data}")

app = Starlette(routes=[
    WebSocketRoute("/ws", websocket_endpoint),
])
  1. Middleware example:
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware

middleware = [
    Middleware(CORSMiddleware, allow_origins=['*'], allow_methods=['*'])
]

app = Starlette(middleware=middleware)

Getting Started

To get started with Starlette, first install it using pip:

pip install starlette

For a production environment, you'll also need an ASGI server like Uvicorn:

pip install uvicorn

Create a file named app.py with the following content:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"message": "Hello, World!"})

app = Starlette(debug=True, routes=[
    Route("/", homepage),
])

Run the application using Uvicorn:

uvicorn app:app --reload

Your Starlette application is now running at http://localhost:8000.

Competitor Comparisons

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • Built-in data validation and serialization using Pydantic models
  • Automatic API documentation generation (Swagger UI and ReDoc)
  • Dependency injection system for easier testing and modularity

Cons of FastAPI

  • Steeper learning curve due to additional features and abstractions
  • Slightly slower performance compared to Starlette's raw speed
  • Larger codebase and more dependencies

Code Comparison

Starlette:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"message": "Hello World!"})

app = Starlette(routes=[Route("/", homepage)])

FastAPI:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return {"item": item}

The code comparison demonstrates FastAPI's built-in data validation and automatic API documentation features, which are not present in Starlette's more minimalistic approach. FastAPI builds upon Starlette, adding higher-level abstractions and developer-friendly features at the cost of some additional complexity.

67,504

The Python micro framework for building web applications.

Pros of Flask

  • Extensive documentation and large community support
  • Rich ecosystem of extensions for added functionality
  • Easier learning curve for beginners

Cons of Flask

  • Slower performance compared to Starlette
  • Lack of built-in async support (requires extensions)
  • More boilerplate code required for basic setup

Code Comparison

Flask:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello, World!'

Starlette:

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route

async def hello(request):
    return PlainTextResponse('Hello, World!')

app = Starlette(routes=[Route('/', hello)])

The code examples show that Flask has a more straightforward setup for basic routing, while Starlette requires a bit more configuration but offers native async support. Flask's decorator-based routing is often considered more intuitive for beginners, whereas Starlette's approach provides more flexibility and is designed with asynchronous programming in mind.

79,088

The Web framework for perfectionists with deadlines.

Pros of Django

  • Full-featured web framework with built-in admin interface, ORM, and authentication system
  • Extensive documentation and large community support
  • Batteries-included approach, providing many out-of-the-box features

Cons of Django

  • Heavier and slower compared to lightweight frameworks
  • Steeper learning curve for beginners due to its comprehensive nature
  • Less flexibility in choosing components or architectural patterns

Code Comparison

Django:

from django.http import HttpResponse

def hello_world(request):
    return HttpResponse("Hello, World!")

Starlette:

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse

app = Starlette()

@app.route("/")
async def hello_world(request):
    return PlainTextResponse("Hello, World!")

Both frameworks allow for easy creation of web applications, but Django's approach is more structured and opinionated, while Starlette offers more flexibility and is designed for asynchronous programming. Django's code is typically more concise for complex applications, while Starlette's code can be more explicit and lightweight for simpler use cases.

21,674

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Pros of Tornado

  • Mature and battle-tested, with a long history of production use
  • Built-in support for WebSockets and long-polling
  • Includes a full-featured HTTP client

Cons of Tornado

  • Less modern syntax compared to Starlette
  • Smaller ecosystem of third-party extensions
  • Not as performant in some benchmarks

Code Comparison

Tornado:

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

app = tornado.web.Application([
    (r"/", MainHandler),
])

Starlette:

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse

app = Starlette()

@app.route("/")
async def homepage(request):
    return PlainTextResponse("Hello, world")

Both Tornado and Starlette are popular Python web frameworks, but they have different design philosophies and target use cases. Tornado is older and more established, with built-in support for various async patterns. Starlette is newer, more lightweight, and designed with modern Python async features in mind. Tornado may be preferred for projects requiring its specific features or those with existing Tornado codebases, while Starlette is often chosen for new projects seeking a modern, high-performance ASGI framework.

14,938

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • More mature and established project with a larger ecosystem
  • Supports both client and server-side HTTP functionality
  • Extensive documentation and community support

Cons of aiohttp

  • Steeper learning curve, especially for beginners
  • More complex API compared to Starlette's simplicity
  • Slower performance in some benchmarks

Code Comparison

aiohttp

from aiohttp import web

async def hello(request):
    return web.Response(text="Hello, World!")

app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)

Starlette

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route

async def hello(request):
    return PlainTextResponse("Hello, World!")

app = Starlette(routes=[Route('/', hello)])

Both aiohttp and Starlette are popular asynchronous web frameworks for Python. aiohttp offers a more comprehensive set of features, including both client and server-side capabilities, making it suitable for complex applications. However, this comes at the cost of a steeper learning curve and more verbose code.

Starlette, on the other hand, focuses on simplicity and performance, making it easier to get started with and potentially faster in certain scenarios. It's particularly well-suited for building APIs and microservices.

The choice between the two often depends on the specific requirements of your project and your familiarity with asynchronous programming in Python.

17,995

Accelerate your web app development | Build fast. Run fast.

Pros of Sanic

  • Built-in support for asynchronous request handlers
  • Includes a web server, eliminating the need for additional ASGI servers
  • Offers WebSocket support out of the box

Cons of Sanic

  • Larger codebase and more dependencies compared to Starlette
  • Less flexibility in terms of middleware and routing customization
  • Steeper learning curve for developers new to asynchronous programming

Code Comparison

Sanic:

from sanic import Sanic
from sanic.response import json

app = Sanic("MyApp")

@app.route("/")
async def hello_world(request):
    return json({"hello": "world"})

Starlette:

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def hello_world(request):
    return JSONResponse({"hello": "world"})

app = Starlette(routes=[
    Route("/", hello_world)
])

Both frameworks offer similar functionality for creating web applications, but Sanic provides a more opinionated structure with built-in features, while Starlette offers a lightweight and flexible foundation for building web applications and APIs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

starlette

✨ The little ASGI framework that shines. ✨


Build Status Package version Supported Python Version


Documentation: https://www.starlette.io

Source Code: https://github.com/encode/starlette


Starlette

Starlette is a lightweight ASGI framework/toolkit, which is ideal for building async web services in Python.

It is production-ready, and gives you the following:

  • A lightweight, low-complexity HTTP web framework.
  • WebSocket support.
  • In-process background tasks.
  • Startup and shutdown events.
  • Test client built on httpx.
  • CORS, GZip, Static Files, Streaming responses.
  • Session and Cookie support.
  • 100% test coverage.
  • 100% type annotated codebase.
  • Few hard dependencies.
  • Compatible with asyncio and trio backends.
  • Great overall performance against independent benchmarks.

Installation

$ pip install starlette

You'll also want to install an ASGI server, such as uvicorn, daphne, or hypercorn.

$ pip install uvicorn

Example

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
    return JSONResponse({'hello': 'world'})

routes = [
    Route("/", endpoint=homepage)
]

app = Starlette(debug=True, routes=routes)

Then run the application using Uvicorn:

$ uvicorn example:app

For a more complete example, see encode/starlette-example.

Dependencies

Starlette only requires anyio, and the following are optional:

  • httpx - Required if you want to use the TestClient.
  • jinja2 - Required if you want to use Jinja2Templates.
  • python-multipart - Required if you want to support form parsing, with request.form().
  • itsdangerous - Required for SessionMiddleware support.
  • pyyaml - Required for SchemaGenerator support.

You can install all of these with pip install starlette[full].

Framework or Toolkit

Starlette is designed to be used either as a complete framework, or as an ASGI toolkit. You can use any of its components independently.

from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)

Run the app application in example.py:

$ uvicorn example:app
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Run uvicorn with --reload to enable auto-reloading on code changes.

Modularity

The modularity that Starlette is designed on promotes building re-usable components that can be shared between any ASGI framework. This should enable an ecosystem of shared middleware and mountable applications.

The clean API separation also means it's easier to understand each component in isolation.


Starlette is BSD licensed code.
Designed & crafted with care.

— ⭐️ —