Skip to content

Commit be8b0a1

Browse files
committed
doc: Added Example Documentation
1 parent c8420e7 commit be8b0a1

1 file changed

Lines changed: 337 additions & 0 deletions

File tree

examples/README.md

Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,337 @@
1+
# WebFiori HTTP Examples
2+
3+
This folder contains practical examples demonstrating how to use the WebFiori HTTP library to create RESTful web services. The examples showcase different features including basic services, parameter handling, and authentication.
4+
5+
## Table of Contents
6+
7+
- [Prerequisites](#prerequisites)
8+
- [Setup](#setup)
9+
- [Available Services](#available-services)
10+
- [1. Hello World Service](#1-hello-world-service-helloworldservicephp)
11+
- [2. Random Number Service](#2-random-number-service-getrandomservicephp)
12+
- [3. Hello with Authentication Service](#3-hello-with-authentication-service-hellowithAuthservicephp)
13+
- [Main Application](#main-application-indexphp)
14+
- [Loader Configuration](#loader-configuration-loaderphp)
15+
- [Key Concepts Demonstrated](#key-concepts-demonstrated)
16+
- [Testing All Services](#testing-all-services)
17+
- [Notes](#notes)
18+
19+
## Prerequisites
20+
21+
- PHP 8.1 or higher
22+
- Composer installed
23+
- WebFiori HTTP library dependencies
24+
25+
## Setup
26+
27+
1. **Install dependencies** (run from the project root directory):
28+
```bash
29+
composer install
30+
```
31+
32+
2. **Navigate to the examples directory**:
33+
```bash
34+
cd examples
35+
```
36+
37+
3. **Start the PHP development server**:
38+
```bash
39+
php -S localhost:8989
40+
```
41+
42+
## Available Services
43+
44+
### 1. Hello World Service (`HelloWorldService.php`)
45+
46+
A basic service that demonstrates simple parameter handling.
47+
48+
**Service Name**: `hello`
49+
**HTTP Methods**: GET
50+
**Parameters**:
51+
- `my-name` (optional, string): Name to include in greeting
52+
53+
**Code Example**:
54+
```php
55+
<?php
56+
57+
require 'loader.php';
58+
59+
use WebFiori\Http\AbstractWebService;
60+
use WebFiori\Http\ParamOption;
61+
use WebFiori\Http\ParamType;
62+
use WebFiori\Http\RequestMethod;
63+
64+
class HelloWorldService extends AbstractWebService {
65+
public function __construct() {
66+
parent::__construct('hello');
67+
$this->setRequestMethods([RequestMethod::GET]);
68+
69+
$this->addParameters([
70+
'my-name' => [
71+
ParamOption::TYPE => ParamType::STRING,
72+
ParamOption::OPTIONAL => true
73+
]
74+
]);
75+
}
76+
public function isAuthorized() {
77+
}
78+
79+
public function processRequest() {
80+
$name = $this->getParamVal('my-name');
81+
82+
if ($name !== null) {
83+
$this->sendResponse("Hello '$name'.");
84+
}
85+
$this->sendResponse('Hello World!');
86+
}
87+
}
88+
```
89+
90+
**Test URLs**:
91+
```bash
92+
# Basic hello
93+
curl "http://localhost:8989?service=hello"
94+
# Response: {"message":"Hello World!","http-code":200}
95+
96+
# Hello with name
97+
curl "http://localhost:8989?service=hello&my-name=ibrahim"
98+
# Response: {"message":"Hello 'ibrahim'.","http-code":200}
99+
```
100+
101+
### 2. Random Number Service (`GetRandomService.php`)
102+
103+
Demonstrates parameter validation and processing with optional integer parameters.
104+
105+
**Service Name**: `get-random-number`
106+
**HTTP Methods**: GET, POST
107+
**Parameters**:
108+
- `min` (optional, integer): Minimum value for random number
109+
- `max` (optional, integer): Maximum value for random number
110+
111+
**Code Example**:
112+
```php
113+
<?php
114+
115+
require 'loader.php';
116+
117+
use WebFiori\Http\AbstractWebService;
118+
use WebFiori\Http\ParamOption;
119+
use WebFiori\Http\ParamType;
120+
use WebFiori\Http\RequestMethod;
121+
122+
class GetRandomService extends AbstractWebService {
123+
public function __construct() {
124+
parent::__construct('get-random-number');
125+
$this->setRequestMethods([
126+
RequestMethod::GET,
127+
RequestMethod::POST
128+
]);
129+
130+
$this->addParameters([
131+
'min' => [
132+
ParamOption::TYPE => ParamType::INT,
133+
ParamOption::OPTIONAL => true
134+
],
135+
'max' => [
136+
ParamOption::TYPE => ParamType::INT,
137+
ParamOption::OPTIONAL => true
138+
]
139+
]);
140+
}
141+
142+
public function isAuthorized() {
143+
// $authHeader = $this->getAuthHeader();
144+
//
145+
// if ($authHeader === null) {
146+
// return false;
147+
// }
148+
//
149+
// $scheme = $authHeader->getScheme();
150+
// $credentials = $authHeader->getCredentials();
151+
152+
//Verify credentials based on auth scheme (e.g. 'Basic', 'Barear'
153+
}
154+
155+
public function processRequest() {
156+
$max = $this->getParamVal('max');
157+
$min = $this->getParamVal('min');
158+
159+
if ($max !== null && $min !== null) {
160+
$random = rand($min, $max);
161+
} else {
162+
$random = rand();
163+
}
164+
$this->sendResponse($random);
165+
}
166+
}
167+
```
168+
169+
**Test URLs**:
170+
```bash
171+
# Random number without bounds
172+
curl "http://localhost:8989?service=get-random-number"
173+
# Response: {"message":"1255598581","http-code":200}
174+
175+
# Random number between 1 and 10
176+
curl "http://localhost:8989?service=get-random-number&min=1&max=10"
177+
# Response: {"message":"7","http-code":200}
178+
179+
# Random number between -4 and 0
180+
curl "http://localhost:8989?service=get-random-number&min=-4&max=0"
181+
# Response: {"message":"-1","http-code":200}
182+
183+
# Invalid parameter type (demonstrates validation)
184+
curl "http://localhost:8989?service=get-random-number&min=-4&max=Super"
185+
# Response: {"message":"The following parameter(s) has invalid values: 'max'.","type":"error","http-code":404,"more-info":{"invalid":["max"]}}
186+
```
187+
188+
### 3. Hello with Authentication Service (`HelloWithAuthService.php`)
189+
190+
Demonstrates Bearer token authentication implementation.
191+
192+
**Service Name**: `hello-with-auth`
193+
**HTTP Methods**: GET
194+
**Authentication**: Bearer token required (`abc123trX`)
195+
**Parameters**:
196+
- `my-name` (optional, string): Name to include in greeting
197+
198+
**Code Example**:
199+
```php
200+
<?php
201+
202+
require 'loader.php';
203+
204+
use WebFiori\Http\AbstractWebService;
205+
use WebFiori\Http\ParamOption;
206+
use WebFiori\Http\ParamType;
207+
use WebFiori\Http\RequestMethod;
208+
use WebFiori\Http\ResponseMessage;
209+
210+
class HelloWithAuthService extends AbstractWebService {
211+
public function __construct() {
212+
parent::__construct('hello-with-auth');
213+
$this->setRequestMethods([RequestMethod::GET]);
214+
215+
$this->addParameters([
216+
'my-name' => [
217+
ParamOption::TYPE => ParamType::STRING,
218+
ParamOption::OPTIONAL => true
219+
]
220+
]);
221+
}
222+
public function isAuthorized() {
223+
//Change default response message to custom one
224+
ResponseMessage::set('401', 'Not authorized to use this API.');
225+
226+
$authHeader = $this->getAuthHeader();
227+
228+
if ($authHeader === null) {
229+
return false;
230+
}
231+
232+
$scheme = $authHeader->getScheme();
233+
$credentials = $authHeader->getCredentials();
234+
235+
if ($scheme != 'bearer') {
236+
return false;
237+
}
238+
239+
return $credentials == 'abc123trX';
240+
}
241+
242+
public function processRequest() {
243+
$name = $this->getParamVal('my-name');
244+
245+
if ($name !== null) {
246+
$this->sendResponse("Hello '$name'.");
247+
}
248+
$this->sendResponse('Hello World!');
249+
}
250+
}
251+
```
252+
253+
**Test URLs**:
254+
```bash
255+
# Without authorization (will fail)
256+
curl "http://localhost:8989?service=hello-with-auth&my-name=ibrahim"
257+
# Response: {"message":"Not authorized to use this API.","type":"error","http-code":401}
258+
259+
# With correct Bearer token
260+
curl -H "Authorization: Bearer abc123trX" "http://localhost:8989?service=hello-with-auth&my-name=ibrahim"
261+
# Response: {"message":"Hello 'ibrahim'.","http-code":200}
262+
```
263+
264+
## Main Application (`index.php`)
265+
266+
The main entry point that registers all services with the WebServicesManager:
267+
268+
```php
269+
<?php
270+
271+
require 'loader.php';
272+
require 'HelloWorldService.php';
273+
require 'GetRandomService.php';
274+
require 'HelloWithAuthService.php';
275+
276+
use HelloWorldService;
277+
use GetRandomService;
278+
use HelloWithAuthService;
279+
use WebFiori\Http\WebServicesManager;
280+
281+
$manager = new WebServicesManager();
282+
$manager->addService(new HelloWorldService());
283+
$manager->addService(new GetRandomService());
284+
$manager->addService(new HelloWithAuthService());
285+
$manager->process();
286+
```
287+
288+
## Loader Configuration (`loader.php`)
289+
290+
Sets up error reporting and autoloading:
291+
292+
```php
293+
<?php
294+
295+
ini_set('display_startup_errors', 1);
296+
ini_set('display_errors', 1);
297+
error_reporting(-1);
298+
299+
require_once '../vendor/autoload.php';
300+
```
301+
302+
## Key Concepts Demonstrated
303+
304+
1. **Service Registration**: How to extend `AbstractWebService` and register services
305+
2. **Parameter Definition**: Using `ParamOption` and `ParamType` for input validation
306+
3. **HTTP Methods**: Supporting different request methods (GET, POST)
307+
4. **Authentication**: Implementing Bearer token authentication with custom error messages
308+
5. **Response Handling**: Using `sendResponse()` to return JSON responses
309+
6. **Parameter Retrieval**: Getting parameter values with `getParamVal()`
310+
311+
## Testing All Services
312+
313+
You can test all the services using the provided test calls:
314+
315+
```bash
316+
# Start the server
317+
php -S localhost:8989
318+
319+
# Test all endpoints
320+
curl "http://localhost:8989?service=hello"
321+
curl "http://localhost:8989?service=hello&my-name=ibrahim"
322+
curl -X POST "http://localhost:8989?service=hello"
323+
curl "http://localhost:8989?service=hello-with-auth&my-name=ibrahim"
324+
curl -H "Authorization: Bearer abc123trX" "http://localhost:8989?service=hello-with-auth&my-name=ibrahim"
325+
curl "http://localhost:8989?service=get-random-number"
326+
curl "http://localhost:8989?service=get-random-number&min=0&max=5"
327+
curl "http://localhost:8989?service=get-random-number&min=-4&max=0"
328+
curl "http://localhost:8989?service=get-random-number&min=-4&max=Super"
329+
```
330+
331+
## Notes
332+
333+
- The POST request to the hello service returns a 415 error because the HelloWorldService only accepts GET requests
334+
- The Bearer token for authentication is hardcoded as `abc123trX` in the HelloWithAuthService
335+
- All responses are returned in JSON format with appropriate HTTP status codes
336+
- Parameter validation is handled automatically by the WebFiori HTTP library based on the parameter definitions
337+
- Invalid parameter types (like passing "Super" for an integer parameter) are automatically caught and return a 404 error with detailed information about which parameters are invalid

0 commit comments

Comments
 (0)