Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[flake8]
max-line-length = 120
max-complexity = 12
select = C,E,F,W,B,B950
ignore = E203, E501, W503
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea/
*.pyc
*.sqlite
14 changes: 14 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
repos:
- repo: https://github.com/pycqa/flake8
rev: '7.3.0' # pick a git hash / tag to point to
hooks:
- id: flake8
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 25.1.0
hooks:
- id: black
17 changes: 17 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM python:3.13.5-bookworm
LABEL authors="nutaro@protonmail.com"

RUN apt update -y
RUN apt upgrade -y
RUN apt install libpq-dev -y

WORKDIR /opt/app

ADD src/ .
ADD requirements.txt requirements.txt

RUN pip install -r requirements.txt


EXPOSE 80
ENTRYPOINT ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "80", "--reload"]
201 changes: 76 additions & 125 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,130 +1,81 @@
# 🧪 Desafio Técnico - Backend Python (FastAPI)
### To run this project you MUST have

## 💸 Conversor de Moedas
* [python3](https://www.python.org/downloads/)
* [pip](https://pip.pypa.io/en/stable/installation/)
* [docker](https://docs.docker.com/engine/install/)
* [docker-compose](https://docs.docker.com/compose/install/)

Você deverá implementar uma aplicação que permita a conversão de valores entre moedas, utilizando **Python com FastAPI** no backend. O frontend pode ser opcionalmente implementado em Vue.js ou React.

> **Importante:** Caso você não tenha experiência com frontend, a entrega pode ser feita exclusivamente com a API.

---

## 📆 Requisitos do Projeto

### ✅ Funcionalidades Principais
- A API deve permitir a conversão entre pelo menos 4 moedas:
- BRL (Real)
- USD (Dólar Americano)
- EUR (Euro)
- JPY (Iene)

- As taxas de câmbio devem ser obtidas da API:
- https://app.currencyapi.com/
- Documentação: https://currencyapi.com/docs

### 🔐 Persistência das Transações
Cada transação realizada deve ser registrada com as seguintes informações:
- ID do usuário
- Moeda de origem e destino
- Valor de origem
- Valor convertido
- Taxa de conversão
- Data/Hora UTC

### 🔍 Endpoint de Consulta
- `GET /transactions?userId=123`

#### Exemplo de retorno:
```json
{
"transactionId": 42,
"userId": 123,
"fromCurrency": "USD",
"toCurrency": "BRL",
"fromValue": 100,
"toValue": 525.32,
"rate": 5.2532,
"timestamp": "2024-05-19T18:00:00Z"
}
to run the tests just
```shell
pytest
```
you must export this env var to run migrations in your database this example uses the database define in the docker-compose
```shell
export DATABASE_URL=postgresql+psycopg2://postgres:example@localhost:5432/postgres
```

### ❌ Casos de Erro
Deverão retornar:
- Código HTTP apropriado
- Mensagem de erro clara e objetiva

---

## 🧪 Testes
- A aplicação deve conter testes unitários e de integração com `pytest`

---

## 📄 README.md
Deve conter:
- Instruções para executar o projeto
- Explicação do propósito
- Principais decisões de arquitetura
- Organização das camadas (ex: routers, services, repositories, models)
- O conteúdo deve estar todo em inglês

---

## 🧰 Itens Desejáveis (Diferenciais)
- Logs estruturados (ex: `loguru`, `structlog`)
- Tratamento de exceções com middlewares
- Documentação automática (Swagger já embutido no FastAPI)
- Linter (ex: `ruff`, `black`, `flake8`)
- Deploy funcional (ex: Render, Railway, Fly.io)
- CI/CD com GitHub Actions

### Frontend (opcional)
- Vue.js 3 + TypeScript ou React + TypeScript
- TailwindCSS
- Axios
- Testes com Cypress, RTL ou Vitest

---

## 🚀 Tecnologias Esperadas

### Backend
- Python 3.10+
- FastAPI
- SQLAlchemy 2.x ou Tortoise ORM
- PostgreSQL ou SQLite
- Pytest

---

## ⭐ Perfil Desejado
- Boas práticas REST
- Arquitetura limpa e escalável
- Conhecimentos em AWS são diferenciais
- Experiência com CI/CD
- Boa comunicação e clareza de código

---

## 📋 Entrega

Para padronizar a entrega e facilitar a análise:

1. Faça um **fork deste repositório** para sua conta pessoal do GitHub.
2. Crie uma **branch com seu nome em snake_case** (exemplo: `joao_silva_souza`).
3. Suba sua solução utilizando **commits organizados e descritivos**.
4. Após finalizar:
- Certifique-se de que o repositório esteja **público**
- Envie o link do seu fork para nossa equipe com:
- **Título:** `Entrega - joao_silva_souza`
- **Descrição:** Nome completo, data da entrega e quaisquer observações que julgar relevantes.

> ✅ **Dica**: Você pode incluir um arquivo `THOUGHTS.md` com decisões técnicas, ideias descartadas e sugestões de melhoria.

---

## 📢 Considerações Finais
- Cite alternativas gratuitas caso use serviços pagos
- Clareza, boas práticas e organização serão avaliadas
- Pode adicionar um `THOUGHTS.md` com decisões técnicas e observações
you must also export the currency_api_key
```shell
export CURRENCY_KEY=your_key
```
to run migrations:
```shell
pip install -r requirements.txt
```
if you get a psycopg2 error it's require libpq-dev
```shell
apt install libpq-dev -y
```
to start the containers
```shell
docker-compose up -d
```
now run the migration
```shell
alembic upgrade head
```
now go to [http://localhost:8080/docs](http://localhost:8080/docs) and try the api through the swagger api or
```shell
curl -X 'POST' \
'http://localhost:8080/transactions' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"value": 10,
"from_currency": "BRL",
"to_currency": "USD",
"user_id": 1
}'
```
for get transaction:
```shell
curl -X 'GET' \
'http://localhost:4200/transactions?user_id=1' \
-H 'accept: application/json'
```

Boa sorte! 🚀
### as a caveat i've included the kubernetes deployments.
just go to the deployment file on kubernetes/deployments line 72 and add you apikey base64 encoded
```shell
echo -n your_key | base64
```
```shell
kubectl apply -f kubernetes/
```
port forward the database
```shell
kubectl port-forward service/postgres-service 8000:9000
```
change your ENV VAR DATABASE_URL
```shell
export DATABASE_URL=postgresql+psycopg2://postgres:example@localhost:8000/postgres
```
run the migrations
```shell
alembic upgrade head
```
port forward the api
```shell
kubectl port-forward service/currency-converter-service 4200:8879
```
the service will be listen at 4200 port
147 changes: 147 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .


# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions

# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = driver://user:password@host/db_name


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
1 change: 1 addition & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
Loading