### Install NeutronAPI Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Installs the NeutronAPI package using pip. This is the initial step to begin using the framework. ```bash pip install neutronapi ``` -------------------------------- ### NeutronAPI Project and App Creation Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Commands to create a new NeutronAPI project and an application within that project. It also shows how to start the development server and run tests. ```bash neutronapi startproject blog cd blog python manage.py startapp posts python manage.py start python manage.py test ``` -------------------------------- ### Start NeutronAPI Development Server Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Command to start the NeutronAPI development server. It also provides the URL to access the running application. ```bash python manage.py start # Visit: http://127.0.0.1:8000/posts ``` -------------------------------- ### NeutronAPI Application Setup with Middleware and Registry Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Python code for setting up a NeutronAPI application, including registering APIs, middlewares (like CompressionMiddleware and AllowedHostsMiddleware), and defining services in the registry for dependency injection. ```python from neutronapi.application import Application from neutronapi.middleware.compression import CompressionMiddleware from neutronapi.middleware.allowed_hosts import AllowedHostsMiddleware from apps.posts.api import PostAPI # Example dependencies class Logger: def info(self, message: str) -> None: print(f"[INFO] {message}") class CacheService: def __init__(self): self._cache = {} def get(self, key: str) -> any: return self._cache.get(key) def set(self, key: str, value: any) -> None: self._cache[key] = value # Modern registry-based dependency injection app = Application( apis=[PostAPI()], middlewares=[ AllowedHostsMiddleware(allowed_hosts=["localhost", "127.0.0.1"]), CompressionMiddleware(minimum_size=512), ], registry={ 'utils:logger': Logger(), 'services:cache': CacheService(), 'services:email': EmailService(), } ) ``` -------------------------------- ### Bash Server Commands Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Provides examples of running the NeutronAPI development and production servers, including options for custom host, port, and worker configuration. ```bash # Development (auto-reload, localhost) python manage.py start # Production (multi-worker, optimized) python manage.py start --production # Custom configuration python manage.py start --host 0.0.0.0 --port 8080 --workers 4 ``` -------------------------------- ### Bash NeutronAPI Management Commands Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Lists common management commands for NeutronAPI projects, such as starting the server, running tests, managing migrations, and creating new apps. ```bash python manage.py start # Start server python manage.py test # Run tests python manage.py migrate # Run migrations python manage.py startapp posts # Create new app ``` -------------------------------- ### Define API Endpoints in NeutronAPI Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Python code demonstrating how to define API resources and endpoints using NeutronAPI's `API` and `endpoint` decorators. It shows how to access registry dependencies and handle request methods like GET and POST. ```python from neutronapi.base import API, endpoint class PostAPI(API): resource = "/posts" name = "posts" @endpoint("/", methods=["GET"]) async def list_posts(self, scope, receive, send, **kwargs): # Access registry dependencies logger = self.registry.get('utils:logger') cache = self.registry.get('services:cache') posts = [{"id": 1, "title": "Hello World"}] return await self.response(posts) @endpoint("/", methods=["POST"]) async def create_post(self, scope, receive, send, **kwargs): # JSON parser is the default; access body via kwargs data = kwargs["body"] # dict return await self.response({"id": 2, "title": data.get("title", "New Post")}) ``` -------------------------------- ### Organize Exceptions by Module in NeutronAPI Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Provides examples of how exceptions are categorized and imported from different modules within the NeutronAPI framework. This includes framework-level exceptions, database-specific exceptions, authentication exceptions, middleware exceptions, and OpenAPI exceptions, promoting modularity in error management. ```python # Module-specific exceptions from neutronapi.api.exceptions import APIException, ValidationError, NotFound from neutronapi.db.exceptions import DoesNotExist, MigrationError, IntegrityError from neutronapi.authentication.exceptions import AuthenticationFailed from neutronapi.middleware.exceptions import RouteNotFound, MethodNotAllowed from neutronapi.openapi.exceptions import InvalidSchemaError # Generic framework exceptions from neutronapi.exceptions import ImproperlyConfigured, ValidationError, ObjectDoesNotExist ``` -------------------------------- ### Configure ASGI Entry Point and Database Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Python code snippet for configuring the ASGI application entry point and database settings in NeutronAPI's settings file. It specifies the module and variable for the ASGI app and the database engine and name. ```python import os # ASGI application entry point (required for server) ENTRY = "apps.entry:app" # module:variable format # Database DATABASES = { 'default': { 'ENGINE': 'aiosqlite', 'NAME': 'db.sqlite3', } } ``` -------------------------------- ### Bash Running Custom Management Command Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Shows how to execute a custom management command ('greet') in NeutronAPI, passing arguments to customize its behavior. ```bash python manage.py greet Alice # Hello, Alice! ``` -------------------------------- ### Python Application with Middlewares Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Illustrates configuring NeutronAPI applications with various middleware, such as compression and allowed hosts, and applying middleware at the endpoint level. ```python from neutronapi.middleware.compression import CompressionMiddleware from neutronapi.middleware.allowed_hosts import AllowedHostsMiddleware app = Application( apis=[PostAPI()], middlewares=[ AllowedHostsMiddleware(allowed_hosts=["localhost", "yourdomain.com"]), CompressionMiddleware(minimum_size=512), # Compress responses > 512 bytes ] ) # Endpoint-level middleware @endpoint("/upload", methods=["POST"], middlewares=[AuthMiddleware()]) async def upload_file(self, scope, receive, send, **kwargs): # This endpoint has auth middleware pass ``` -------------------------------- ### Bash Testing and Development Tooling Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Demonstrates how to run tests and utilize development tooling like Black and Flake8 for code formatting and linting within a NeutronAPI project. ```bash # SQLite (default) python manage.py test # Specific tests python manage.py test app.tests.test_models.TestUser.test_creation # Dev tooling (only neutronapi/ is targeted) black neutronapi flake8 neutronapi ``` -------------------------------- ### Python API with Type Hints Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Demonstrates NeutronAPI's full type hint support for IDE integration, including typed registry access for services like caching and logging. ```python from typing import Dict, List, Optional from neutronapi.base import API, Response, endpoint from neutronapi.application import Application class TypedAPI(API): resource = "/api" @endpoint("/users", methods=["GET"]) async def get_users(self, scope: Dict[str, Any], receive, send) -> Response: # Full type support with autocomplete cache: CacheService = self.registry.get('services:cache') users: List[Dict[str, str]] = cache.get('users') or [] return await self.response(users) # Type-safe registry access def get_typed_dependency[T](app: Application, key: str) -> Optional[T]: return app.get_registry_item(key) logger = get_typed_dependency[Logger](app, 'utils:logger') ``` -------------------------------- ### Data Handling and File Uploads Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Demonstrates how to handle JSON data and file uploads using different parsers. ```APIDOC ## POST /api/data ### Description Handles incoming JSON data. ### Method POST ### Endpoint /api/data ### Request Body - **body** (dict) - Required - Parsed JSON dictionary. ### Response #### Success Response (200) - **received** (dict) - The received JSON data. #### Response Example ```json { "received": { "key": "value" } } ``` ## POST /upload ### Description Handles file uploads and form data. ### Method POST ### Endpoint /upload ### Parameters #### Request Body - **files** (dict) - Uploaded files. - **form** (dict) - Form fields. ### Response #### Success Response (200) - **status** (str) - Indicates the upload status. #### Response Example ```json { "status": "uploaded" } ``` ``` -------------------------------- ### Advanced Registry Usage for Dependency Injection Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Illustrates advanced usage of NeutronAPI's registry for dependency injection with type safety. It defines protocols for services, provides implementations, and shows how to register and retrieve these services within an API endpoint. This promotes cleaner code and easier testing. ```python from neutronapi.application import Application from neutronapi.api import API, endpoint from typing import Protocol # Define interfaces for better type safety class EmailServiceProtocol(Protocol): async def send(self, to: str, subject: str, body: str) -> None: ... class MetricsProtocol(Protocol): def increment(self, metric: str) -> None: ... # Implementation class SMTPEmailService: async def send(self, to: str, subject: str, body: str) -> None: # SMTP implementation pass class PrometheusMetrics: def increment(self, metric: str) -> None: # Prometheus implementation pass # Assuming StructuredLogger and JWTAuthModule are defined elsewhere class StructuredLogger: pass class JWTAuthModule: pass # Register with clear namespacing app = Application( registry={ 'services:email': SMTPEmailService(), 'services:metrics': PrometheusMetrics(), 'utils:logger': StructuredLogger(), 'modules:auth': JWTAuthModule(), } ) # Usage with type safety class OrderAPI(API): @endpoint("/orders", methods=["POST"]) async def create_order(self, scope, receive, send, **kwargs): email: EmailServiceProtocol = self.registry.get('services:email') metrics: MetricsProtocol = self.registry.get('services:metrics') # Your business logic here metrics.increment('orders.created') await email.send('user@example.com', 'Order Confirmed', 'Thanks!') return await self.response({"status": "created"}) ``` -------------------------------- ### NeutronAPI Universal Registry System Usage Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Python code illustrating the NeutronAPI's universal registry system for dependency injection. It shows how to register dependencies, access them in APIs with type safety, and use registry utility methods. ```python from neutronapi.application import Application # Register dependencies with namespace:name pattern app = Application( registry={ 'utils:logger': Logger(), 'utils:cache': RedisCache(), 'services:email': EmailService(), 'services:database': DatabaseService(), 'modules:auth': AuthModule(), } ) # Access in APIs class UserAPI(API): @API.endpoint("/register", methods=["POST"]) async def register(self, scope, receive, send, **kwargs): # Type-safe access with IDE support logger = self.registry.get('utils:logger') email = self.registry.get('services:email') logger.info("User registration started") await email.send_welcome_email(user_data) return await self.response({"status": "registered"}) # Dynamic registration app.register('utils:metrics', MetricsCollector()) app.register('services:payment', PaymentProcessor()) # Registry utilities print(app.list_registry_keys()) # All keys print(app.list_registry_keys('utils')) # Just utils namespace print(app.has_registry_item('services:email')) # True ``` -------------------------------- ### Python Background Task and API Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Illustrates how to define background tasks with specific frequencies and create simple API endpoints within the NeutronAPI application. ```python from neutronapi.background import Task, TaskFrequency from neutronapi.base import API, endpoint from neutronapi.application import Application class CleanupTask(Task): name = "cleanup" frequency = TaskFrequency.MINUTELY async def run(self, **kwargs): print("Cleaning up logs...") class PingAPI(API): resource = "/ping" @endpoint("/", methods=["GET"]) async def ping(self, scope, receive, send, **kwargs): return await self.response({"status": "ok"}) # Add to application app = Application( apis=[PingAPI()], tasks={"cleanup": CleanupTask()} ) ``` -------------------------------- ### OpenAPI Documentation Generation Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Shows how to automatically generate OpenAPI 3.0 specifications for your APIs. ```APIDOC ## GET /v1/users/ ### Description Lists all users. This is an example of an automatically discovered API endpoint. ### Method GET ### Endpoint /v1/users/ ### Parameters *(No parameters specified for this endpoint in the provided text.)* ### Response #### Success Response (200) - **users** (list) - A list of user objects. #### Response Example ```json { "users": [] } ``` ## GET /debug/status ### Description Provides status information for debugging. This endpoint is hidden by default but can be included in documentation generation. ### Method GET ### Endpoint /debug/status ### Parameters *(No parameters specified for this endpoint in the provided text.)* ### Response #### Success Response (200) - **debug** (bool) - A boolean indicating the debug status. #### Response Example ```json { "debug": true } ``` ``` -------------------------------- ### Error Handling Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Details the exception hierarchy and how to raise custom exceptions. ```APIDOC ## GET /users/ ### Description Retrieves a user by their ID, with validation and not found error handling. ### Method GET ### Endpoint /users/ ### Parameters #### Path Parameters - **user_id** (int) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - *(User object details not specified in the provided text.)* #### Response Example ```json { "user_id": 123, "name": "John Doe" } ``` #### Error Responses - **400 Bad Request** (ValidationError): If User ID is missing. - **404 Not Found** (NotFound): If the user is not found. - **422 Unprocessable Entity** (BusinessLogicError): For custom business logic errors. ``` -------------------------------- ### Python ORM Database Queries Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Illustrates basic database operations using NeutronAPI's ORM, including fetching all records, filtering by criteria, and creating new records. ```python from neutronapi.db.models import Model from neutronapi.db.fields import CharField, IntegerField, DateTimeField class Post(Model): title = CharField(max_length=200) content = TextField() created_at = DateTimeField(auto_now_add=True) # Basic queries await Post.objects.all() await Post.objects.filter(title="My Post") await Post.objects.create(title="New Post", content="...") ``` -------------------------------- ### Advanced Registry Usage Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Illustrates the use of a registry for managing dependencies and services within the API. ```APIDOC ## POST /orders ### Description Creates a new order, utilizing registered services for email and metrics. ### Method POST ### Endpoint /orders ### Parameters #### Request Body *(Details not specified in the provided text for this specific endpoint's request body.)* ### Response #### Success Response (200) - **status** (str) - The status of the order creation. #### Response Example ```json { "status": "created" } ``` ``` -------------------------------- ### Generate OpenAPI 3.0 Specifications with NeutronAPI Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Demonstrates how to use `OpenAPIGenerator` from NeutronAPI to automatically create OpenAPI 3.0 specifications for your APIs. It shows how to define APIs, mark them as hidden, and generate documentation for public-facing APIs or complete documentation including hidden ones. ```python from neutronapi.openapi.openapi import OpenAPIGenerator from neutronapi.api import API, endpoint # Basic API - automatically discovered class UserAPI(API): resource = "/v1/users" name = "users" @API.endpoint("/", methods=["GET"], name="list") async def list_users(self, scope, receive, send, **kwargs): return await self.response({"users": []}) # Internal/debug API - hidden by default class DebugAPI(API): resource = "/debug" name = "debug" hidden = True # Excluded from docs by default @API.endpoint("/status", methods=["GET"], name="status") async def debug_status(self, scope, receive, send, **kwargs): return await self.response({"debug": True}) # Generate public API docs (excludes hidden APIs) async def generate_public_docs(): apis = {"users": UserAPI(), "debug": DebugAPI()} generator = OpenAPIGenerator(title="My API", version="1.0.0") spec = await generator.generate(source=apis) # Result: Only includes /v1/users endpoints # Generate complete docs (includes everything) async def generate_complete_docs(): apis = {"users": UserAPI(), "debug": DebugAPI()} generator = OpenAPIGenerator( title="Complete API", include_all=True # Include hidden APIs and private endpoints ) spec = await generator.generate(source=apis) # Result: Includes both /v1/users and /debug endpoints ``` -------------------------------- ### Python Custom Management Command Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Demonstrates how to create a custom management command in NeutronAPI by extending the BaseCommand class, similar to Django's structure. ```python # apps/blog/commands/greet.py from neutronapi.commands.base import BaseCommand class Command(BaseCommand): help = "Greet a user" def handle(self, *args, **options): name = args[0] if args else "World" self.success(f"Hello, {name}!") return 0 ``` -------------------------------- ### Define API Endpoints with JSON and File Upload Parsers Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Demonstrates how to define API endpoints using NeutronAPI decorators. It shows a basic JSON POST endpoint and a file upload endpoint supporting multipart and form data parsing. Parses are configured using `MultiPartParser` and `FormParser`. ```python from neutronapi.api import endpoint from neutronapi.parsers import MultiPartParser, FormParser # Default: JSON parser @endpoint("/api/data", methods=["POST"]) async def json_data(self, scope, receive, send, **kwargs): data = kwargs["body"] # Parsed JSON dict return await self.response({"received": data}) # Custom parsers @endpoint("/upload", methods=["POST"], parsers=[MultiPartParser(), FormParser()]) async def upload_file(self, scope, receive, send, **kwargs): files = kwargs["files"] # Uploaded files form_data = kwargs["form"] # Form fields return await self.response({"status": "uploaded"}) ``` -------------------------------- ### Python Database Model Definition Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Shows the definition of a database model 'User' using NeutronAPI's ORM, specifying fields like name, age, and creation timestamp. ```python from neutronapi.db.models import Model from neutronapi.db.fields import CharField, IntegerField, DateTimeField class User(Model): name = CharField(max_length=100) age = IntegerField() created_at = DateTimeField(auto_now_add=True) ``` -------------------------------- ### Python Parser Imports Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Imports various parser classes provided by the NeutronAPI library, including FormParser, MultiPartParser, and BinaryParser. ```python from neutronapi.parsers import FormParser, MultiPartParser, BinaryParser ``` -------------------------------- ### Implement Custom Error Handling with NeutronAPI Exceptions Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Shows how to implement robust error handling within NeutronAPI endpoints. It demonstrates raising built-in exceptions like `ValidationError` and `NotFound`, and how to define custom exceptions inheriting from `APIException` for specific business logic errors. The code includes a basic database lookup simulation. ```python from neutronapi.api import endpoint from neutronapi.api.exceptions import ValidationError, NotFound, APIException # Assume get_user_from_db is an async function that fetches user data async def get_user_from_db(user_id: int): # Mock database lookup if user_id == 1: return {"id": 1, "name": "John Doe"} return None @endpoint("/users/", methods=["GET"]) async def get_user(self, scope, receive, send, **kwargs): user_id = kwargs["user_id"] if not user_id: raise ValidationError("User ID is required") user = await get_user_from_db(user_id) if not user: raise NotFound("User not found") return await self.response(user) # Custom exceptions class BusinessLogicError(APIException): status_code = 422 def __init__(self, message: str = "Business logic error"): super().__init__(message, type="business_error") ``` -------------------------------- ### Generate OpenAPI Spec for All Endpoints Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Generates a complete OpenAPI specification that includes all defined API endpoints. This is a convenience function for comprehensive documentation. ```python from neutronapi.openapi.openapi import generate_all_endpoints_openapi spec = await generate_all_endpoints_openapi(apis, title="All Endpoints") ``` -------------------------------- ### Python ORM Full-Text Search Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Showcases NeutronAPI's full-text search capabilities, including searching across text fields, field-specific searches, and ranking results. ```python # Search across text fields await Post.objects.search("python framework") # Field-specific search await Post.objects.filter(content__search="database") # Ranked results (PostgreSQL/SQLite FTS5) await Post.objects.search("api").order_by_rank() ``` -------------------------------- ### Generate OpenAPI Spec Excluding Patterns Source: https://github.com/aaronkazah/neutronapi/blob/main/README.md Generates an OpenAPI specification while excluding specific API paths like '/debug/*' and '/internal/*'. This is useful for keeping internal or non-public APIs out of the generated documentation. ```python async def generate_filtered_docs(): apis = {"users": UserAPI(), "debug": DebugAPI()} generator = OpenAPIGenerator( title="Filtered API", exclude_patterns=["/debug/*", "/internal/*"] ) spec = await generator.generate(source=apis) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.