# Http tools

Async http server as component
<details>
<summary>Копирование кода для тестов</summary>

```sh
cp -r $ORIGIN_DIR/http_tools ./http_tools
```

</details>

## Basic example
Echo server
```python
import asyncio

from http_tools import HttpServer, JsonableAnswer

async def amain():
    server = HttpServer(HttpServer.Config(port=7777), HttpServer.Context(instance_id="readme"))
    server.register_handler('/echo', lambda x: JsonableAnswer(x.key_value_arguments))
    async with server:
        print("Server started")
        await asyncio.sleep(10 ** 10)

asyncio.run(amain())
```
Http server started 
```
Server started
```
Example request
```bash
curl --location "http://0.0.0.0:7777/echo?one=1&two=2"
```
Expected answer
```json
{"one": "1", "two":  "2"}
```


## Form data example
Server with endpoint accepting two id collections
```python
import asyncio

from http_tools import HttpServer, JsonableAnswer, IncomingRequest

def merge_collections(request: IncomingRequest) -> JsonableAnswer:
    assert (token := request.parsed_body['token'].parse()) == 'secret', f'Expected "secret", got {token}'
    result = set(request.parsed_body['ids'].parse()) & set(request.parsed_body['other_ids'].parse())
    return JsonableAnswer(result)

async def amain():
    server = HttpServer(HttpServer.Config(port=7777), HttpServer.Context(instance_id="readme"))
    server.register_handler('/merge', merge_collections)
    async with server:
        print("Server started")
        await asyncio.sleep(10 ** 10)

asyncio.run(amain())
```
After start this code will print: 
```
Server started
```
Example request
```bash
curl -X POST --location "http://127.0.0.1:7777/merge" \
    -H "authorization: Bearer GGKYP6MBYQ" \
    -F "ids=[1,2,3];filename=ids.json;type=application/json" \
    -F "other_ids=[2,3,4];type=application/json" \
    -F "token=secret"
```
Expected answer
```json
[2, 3]
```