nice-server-api 0.2.0
A lightweight Python library for simplified server (Flask) and client (requests) API interactions
Requires Python: >=3.6

# NiceServerAPI

**NiceServerAPI** — a lightweight, user-friendly Python library for building server and client applications. Powered by Flask for the server and `requests` for the client, it lets you write simple Python functions while automatically handling routes and requests!

[![PyPI version](https://img.shields.io/pypi/v/nice-server-api.svg)](https://pypi.org/project/nice-server-api/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.6+](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org/downloads/)

## Features
- **Simple Server Setup**: Define functions, and routes are created automatically.
- **Easy Client Calls**: Connect to server functions with a single method.
- **Database Support**: Built-in user management with SQLite (login, register, update, etc.).
- **Flexible and Extensible**: Add custom functions, manage tables, and export data.

## Installation

Install via pip:

```bash
pip install nice-server-api
```

Dependencies
Python >= 3.6

Flask >= 2.0.0

requests >= 2.25.0

bcrypt >= 4.0.0

# Quick Start
1. Creating a Server
Create a file, e.g., server_app.py.

Define Python functions for your logic.

Register them with server.register_function().

Initialize a database for user management (optional).

Run the server.

Example: server_app.py
python

from nice_server_api import NiceServer

# Create a server on port 5000
server = NiceServer(port=5000)

# Initialize database for users
server.Login(db_path="users.db", table_name="users", id=int, password=str, balance=float)

# Register a user
server.register(id=1, password="secret", balance=100.5)

# Define custom functions
def hello(url, name="Guest"):
    return f"Hello, {name} from {url}!"

def add(url, a=0, b=0):
    return int(a) + int(b)

# Register functions
server.register_function(hello)
server.register_function(add)

# Run the server
server.run()

What Happens:
Server runs at http://localhost:5000.

/hello (e.g., http://localhost:5000/hello?name=Alex) returns a greeting.

/add (e.g., http://localhost:5000/add?a=2&b=3 or POST {"a": 2, "b": 3}) adds numbers.

Users are stored in users.db with default values (int/float: 0, str: None).

2. Creating a Client
Create a file, e.g., client_app.py.

Use NiceClient to connect to the server.

Call functions by name with server.connect().

Example: client_app.py
python

from nice_server_api import NiceClient

# Create a client
server = NiceClient("http://localhost:5000")

# Call server functions
print(server.connect("hello", name="Alex"))  # {'result': 'Hello, Alex from /hello!', 'status': 'success'}
print(server.connect("add", 2, 3))           # {'result': 5, 'status': 'success'}
print(server.connect("add", a=10, b=20))     # {'result': 30, 'status': 'success'}

What Happens:
Connects to http://localhost:5000.

connect("hello", name="Alex") sends a POST request with {"name": "Alex"}.

connect("add", 2, 3) sends a GET request with arg0=2&arg1=3.

Responses include result, status, and error (if applicable).

How It Works
Server
Initialize: Create a NiceServer(port, host="0.0.0.0", debug=False).

Database: Use Login(db_path, table_name, **columns) to set up a SQLite table.

Routes: Register functions with server.register_function(func)—URL is the function name (e.g., hello → /hello).
Functions take url (auto-passed) and params from GET (query) or POST (JSON).

Returns JSON: {"result": ..., "status": "success"}.

Run: Call server.run().

Client
Initialize: Create a NiceClient(server_address).

Call Functions: Use connect(function_name, *args, **kwargs):
function_name: Name of the server function (e.g., "hello").

*args: Positional args become GET params (arg0, arg1, ...).

**kwargs: Named args become JSON in a POST request.

Response: Dict with result, status ("success" or "error"), and error (if failed).

Database Methods
**Login(db_path, table_name, columns): Sets up a SQLite table with columns (e.g., id=int, password=str).

**register(kwargs): Adds a user, auto-filling missing values (int/float: 0, str: None).

**get_info(kwargs): Finds a user by two params, returns all fields or None.

**update_user(identifier, id_value, kwargs): Updates user fields by identifier (e.g., id).

**delete_user(kwargs): Deletes a user by two params.

count_users(): Returns the number of users.

add_column(name, type): Adds a column (e.g., email=str).

drop_column(name): Removes a column.

clear_table(): Deletes all records.

hash_password(password): Hashes a password with bcrypt for security.

export_to_csv(path): Exports the table to a CSV file.

Examples
Example 1: User Management
Server (server_app.py):
python

from nice_server_api import NiceServer

server = NiceServer(port=5000)
server.Login(db_path="users.db", table_name="users", id=int, password=str, balance=float)

# Register and update users
server.register(id=1, password="secret", balance=100.5)
server.update_user("id", 1, password="newpass", balance=200.0)

# Get user info
user = server.get_info(id=1, password="newpass")
print(user)  # {'id': 1, 'password': 'newpass', 'balance': 200.0}

# Export and clear
server.export_to_csv("users.csv")
server.clear_table()
server.run()

Example 2: Custom Functions
Server (server_app.py):
python

from nice_server_api import NiceServer

server = NiceServer(port=5000)

def multiply(url, x=1, y=1):
    return int(x) * int(y)

server.register_function(multiply)
server.run()

Client (client_app.py):
python

from nice_server_api import NiceClient

server = NiceClient("http://localhost:5000")
print(server.connect("multiply", 4, 5))      # {'result': 20, 'status': 'success'}
print(server.connect("multiply", x=3, y=7))  # {'result': 21, 'status': 'success'}

Tips
Running: Start the server in one terminal, the client in another.

Errors: Failed calls return {"error": "message", "status": "error"}.

Security: Use hash_password() before storing passwords.

Extending: Add custom functions—parameters are auto-handled.

Project Structure

NiceServerAPI/
├── nice_server_api/
│   ├── __init__.py        # Library initialization
│   ├── server.py          # Server logic (Flask)
│   ├── client.py          # Client logic (requests)
│   └── utils.py           # Utility functions
├── tests/
│   ├── test_server.py     # Server tests
│   └── test_client.py     # Client tests
├── README.md              # Documentation
├── pyproject.toml         # Build configuration
├── LICENSE                # MIT License
└── .gitignore             # Git ignore file

Contributing
Found a bug? Have a feature idea? Open an issue at GitHub.