nova-api/api/main.py

77 lines
1.9 KiB
Python
Raw Normal View History

2023-07-19 23:51:28 +02:00
"""FastAPI setup."""
2023-06-23 02:18:28 +02:00
import fastapi
2023-08-24 14:57:36 +02:00
import pydantic
2023-06-23 02:18:28 +02:00
2023-08-05 02:30:42 +02:00
from rich import print
2023-06-23 02:18:28 +02:00
from dotenv import load_dotenv
2023-09-14 20:43:24 +02:00
2023-08-24 14:57:36 +02:00
from bson.objectid import ObjectId
2023-10-09 19:09:01 +02:00
from fastapi.middleware.cors import CORSMiddleware
2023-09-14 20:43:24 +02:00
2023-08-27 04:29:16 +02:00
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from slowapi.util import get_remote_address
2023-08-27 04:29:16 +02:00
from slowapi import Limiter, _rate_limit_exceeded_handler
2023-08-01 02:38:55 +02:00
import core
2023-08-27 04:29:16 +02:00
import handler
2023-06-23 02:18:28 +02:00
load_dotenv()
app = fastapi.FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*']
)
2023-08-01 02:38:55 +02:00
app.include_router(core.router)
2023-08-27 04:29:16 +02:00
limiter = Limiter(
swallow_errors=True,
key_func=get_remote_address,
default_limits=[
'2/second',
'30/minute',
'400/hour'
2023-08-27 04:29:16 +02:00
])
2023-08-27 04:29:16 +02:00
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)
2023-06-23 02:18:28 +02:00
@app.on_event('startup')
async def startup_event():
"""Runs when the API starts up."""
2023-08-24 14:57:36 +02:00
# https://stackoverflow.com/a/74529009
pydantic.json.ENCODERS_BY_TYPE[ObjectId]=str
2023-06-23 02:18:28 +02:00
@app.get('/')
async def root():
2023-08-13 17:12:35 +02:00
"""
Returns general information about the API.
2023-08-13 17:12:35 +02:00
"""
2023-06-23 02:18:28 +02:00
return {
'hi': 'Welcome to the Nova API!',
'learn_more_here': 'https://nova-oss.com',
'github': 'https://github.com/novaoss/nova-api',
'core_api_docs_for_nova_developers': '/docs',
'ping': 'pong'
2023-06-23 02:18:28 +02:00
}
2023-08-27 04:29:16 +02:00
@app.route('/v1/{path:path}', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
async def v1_handler(request: fastapi.Request):
2023-09-14 18:18:19 +02:00
res = await handler.handle(incoming_request=request)
return res
@limiter.limit('100/minute', '1000/hour')
@app.route('/enterprise/v1/{path:path}', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
async def enterprise_handler(request: fastapi.Request):
res = await handler.handle(incoming_request=request)
return res