Python - api()
Creates a new HTTP API.
from nitric.resources import apipublicApi = api("public")
Parameters
- Name
name
- Required
- Required
- Type
- string
- Description
The unique name of this API within the app. Subsequent calls to
api
with the same name will return the same object.
- Name
options
- Optional
- Optional
- Type
- object
- Description
Additional options when creating the API.
- Name
path
- Optional
- Optional
- Type
- string
- Description
Base path for all routes in the API.
- Name
middleware
- Optional
- Optional
- Type
- List[Middleware]
- Description
Middleware to apply to all routes and methods of the API.
- Name
securityDefinitions
- Optional
- Optional
- Type
- dict[str, SecurityDefinition]
- Description
Security definitions defined by this API.
- Name
security
- Optional
- Optional
- Type
- dict[str, List[str]]
- Description
Security rules to apply with scopes to the entire API. Keys must match a
securityDefinition
.
SecurityDefinition Parameters
- Name
issuer
- Required
- Required
- Type
- string
- Description
The issuer for the JWT tokens e.g.
https://account.region.auth0.com
.
- Name
audiences
- Required
- Required
- Type
- string[]
- Description
The
aud
that will be applied to JWT tokens from the issuer.
Notes
The middleware
property on the options
param is useful for applying universal middleware such as CORS headers, across an entire API from a single place.
Examples
Create an API
from nitric.resources import apipublicApi = api("public")
Create an API with universal middleware
from nitric.resources import api, ApiOptionsfrom myapp.middleware import authpublicApi = api("public", ApiOptions(middleware=[auth]))
Define middleware
async def auth(ctx, nxt: HttpMiddleware):# Perform auth validation.return await nxt(ctx)
Notes
Middleware services are supplied a HttpContext
object and a next()
function which calls the next middleware in the chain.
Create an API with a base path
If you need to put all the routes in your api below a shared base path, you can do that with the path
option. In this example we ensure all routes start with /api/v1/
before the route specific path.
from nitric.resources import api, ApiOptionspublicApi = api("public", ApiOptions(path="/api/v1/"))
Apply JWT authentication to an API
from nitric.resources import api, ApiOptionsfrom nitric.resources.apis import JwtSecurityDefinitionpublicApi = api("public", ApiOptions(security_definitions={"user": JwtSecurityDefinition(issuer="https://example-issuer.com",audiences=['YOUR-AUDIENCES'])},security={"user": []}))