Skip to main content

API Star Overview

API Star is a high-performance API framework that allows you to build web APIs with ease.

It is designed to be simple, intuitive, and scalable, making it an ideal choice for building both small and large-scale applications.

History

API Star was created by Tom Christie, the same developer behind the popular Django REST framework. It was first released in 2017 and has since gained a lot of popularity within the Python community.

Features

1. Type Annotations

API Star leverages the power of Python's type annotations to provide automatic request and response validation. This allows you to define the expected types for your input and output data, helping to catch potential bugs early on.

Here's an example of how to use type annotations with API Star:

from apistar import http, App, Route

def hello(name: str) -> dict:
return {'message': f'Hello, {name}!'}

routes = [
Route('/hello/{name}/', method='GET', handler=hello),
]

app = App(routes=routes)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

In this example, the hello function takes a parameter name of type str and returns a dictionary. API Star will automatically validate the type of the name parameter and the return value, ensuring that the API contract is enforced.

2. Automatic Documentation

API Star generates comprehensive documentation for your API automatically. This documentation includes details about the available endpoints, the expected request and response formats, and any additional parameters or headers required.

To view the generated documentation, simply navigate to /docs in your web browser after running your API.

3. Authentication and Permissions

API Star provides built-in support for authentication and permissions. You can easily integrate popular authentication schemes like OAuth, JWT, or API keys into your API.

Here's an example of how to use authentication with API Star:

from apistar import http, App, Route, annotate

def require_authentication() -> annotate(permissions=[IsAuthenticated]):
pass

def hello(user: User) -> dict:
return {'message': f'Hello, {user.username}!'}

routes = [
Route('/hello/', method='GET', handler=hello, permissions=[require_authentication]),
]

app = App(routes=routes)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

In this example, the require_authentication function is used as a permission decorator for the hello endpoint. This ensures that only authenticated users can access the endpoint. The user parameter is automatically populated with the authenticated user object.

4. Database Integration

API Star integrates seamlessly with popular databases like PostgreSQL, MySQL, and SQLite. You can easily define models and perform database operations using the built-in ORM.

Here's an example of how to use the ORM with API Star:

from apistar import http, App, Route, annotate
from apistar.backends import SQLAlchemy

app = App()
app.add_database(SQLAlchemy('sqlite:///mydatabase.db'))

class User(app.orm.Model):
__tablename__ = 'users'

id = app.orm.Column(app.orm.Integer, primary_key=True)
username = app.orm.Column(app.orm.String)

def list_users() -> list[User]:
return User.query.all()

routes = [
Route('/users/', method='GET', handler=list_users),
]

app = App(routes=routes)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

In this example, the User model is defined using the SQLAlchemy ORM. The list_users function retrieves all the users from the database and returns them as a list of User objects.

5. Middleware Support

API Star supports the use of middleware, allowing you to modify requests and responses at various stages of the request/response cycle. This is useful for tasks like authentication, logging, error handling, and more.

Here's an example of how to use middleware with API Star:

from apistar import http, App, Route

def authentication_middleware(request: http.Request, handler) -> http.Response:
# Perform authentication logic here
authenticated = True

if not authenticated:
return http.Response('Unauthorized', status=401)

response = handler(request)
return response

def hello() -> dict:
return {'message': 'Hello, World!'}

routes = [
Route('/', method='GET', handler=hello),
]

middleware = [authentication_middleware]

app = App(routes=routes, middleware=middleware)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

In this example, the authentication_middleware function intercepts the request and performs authentication logic. If the user is not authenticated, a 401 Unauthorized response is returned. Otherwise, the handler function is called and the response is returned as-is.

Examples

Example 1: Hello World

from apistar import http, App, Route

def hello() -> dict:
return {'message': 'Hello, World!'}

routes = [
Route('/', method='GET', handler=hello),
]

app = App(routes=routes)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

Output:

{"message": "Hello, World!"}

Example 2: URL Parameters

from apistar import http, App, Route

def hello(name: str) -> dict:
return {'message': f'Hello, {name}!'}

routes = [
Route('/hello/{name}/', method='GET', handler=hello),
]

app = App(routes=routes)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

Output:

GET /hello/John/
{"message": "Hello, John!"}

Example 3: Query Parameters

from apistar import http, App, Route

def hello(name: str, age: int) -> dict:
return {'message': f'Hello, {name}! You are {age} years old.'}

routes = [
Route('/hello/', method='GET', handler=hello),
]

app = App(routes=routes)

if __name__ == '__main__':
app.serve('127.0.0.1', 8000)

Output:

GET /hello/?name=John&age=25
{"message": "Hello, John! You are 25 years old."}

For more information, you can visit the official API Star documentation.