openapi: 3.0.3 info: title: "API de Livros - FIAP Machine Learning Tech Challenge 1" description: | ## 📚 API RESTful para gerenciamento de livros obtidos via web scraping de https://books.toscrape.com ### Principais recursos: - **Cadastro e login e informações de usuários** - **Autenticação via JWT (Bearer Token)** - **Consulta de livros**: listagem, busca por ID ou por título/categoria, mais avaliados e por média de preços - **Estatísticas** gerais e por categoria - **Trigger de scraping via endpoint** para atualizar os dados - **Health-check** da API ### Instruções de uso ### 1. Selecione um servidor **Em servers escolha:** - **Produção**: `https://fiap-machine-learning-tech-challeng.vercel.app - Vercel server` - **Local**: `http://127.0.0.1:8000 - Execução local` ### 1. Cadastro de usuário **Cadastre um usuário no `POST /users` ou utilize o de teste já existente:** - **Username**: `test_user` - **Password**: `test12345` ### 2. Realizar Autenticação para obter o Token de Acesso `POST /auth/login` **Parâmetros da Requisição (Body):**: - **Username**: `test_user` - **Password**: `test12345` Retorna um JSON com `access_token`, `refresh_token` e `token_type` ### 3. Usar o Token para acessar Endpoints protegidos Inclua o token no header: ``` Authorization: Bearer ``` version: "1.0.0" servers: - url: "https://fiap-machine-learning-tech-challeng.vercel.app" description: "Vercel server" - url: "http://127.0.0.1:8000" description: "Execução local" components: schemas: ErrorResponse: type: object properties: detail: type: string required: - detail Health: type: object properties: status: type: string example: "ok" required: - status User: type: object properties: id: type: integer example: 1 username: type: string example: "alice" required: - id - username UserCreate: type: object properties: username: type: string example: "bob" password: type: string example: "strongpassword" required: - username - password UserOut: type: object properties: id: type: integer example: 1 username: type: string example: "novo_usuario" required: - id - username Token: type: object properties: access_token: type: string example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." refresh_token: type: string example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." token_type: type: string example: "bearer" required: - access_token - refresh_token - token_type Book: type: object properties: id: type: integer example: 824 title: type: string example: "A Light in the Attic" price: type: number format: float example: 51.77 availability: type: string example: "In Stock" rating: type: string example: "Three" category: type: string example: "Poetry" image_url: type: string example: "https://books.toscrape.com/media/cache/fe/72/fe72f0532301ec28892ae79a629a293c.jpg" required: - id - title - price - availability - rating - category - image_url Category: type: string properties: name: type: string example: "Poetry" required: - name Stats: type: object properties: total_books: type: integer example: 1000 average_price: type: number format: float example: 35.12 rating_distribution: type: object description: "Distribution of books by rating" example: Five: 197 Four: 181 One: 228 Three: 206 Two: 199 required: - total_books - average_price - rating_distribution CategoryStats: type: object properties: category: type: string example: "Poetry" total_books: type: integer example: 42 average_price: type: number format: float example: 28.99 required: - category - total_books - average_price securitySchemes: BearerAuth: type: http scheme: bearer bearerFormat: JWT security: - BearerAuth: [] paths: /api/v1/health: get: tags: ["Health"] summary: Health check description: Verifica status da API e conectividade com os dados. responses: '200': description: API está saudável content: application/json: schema: $ref: "#/components/schemas/Health" /api/v1/users: post: tags: ["Users"] summary: Cria um novo usuário description: Registra um novo usuário no sistema requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UserCreate" responses: '200': description: User created successfully content: application/json: schema: $ref: "#/components/schemas/UserCreate" '409': description: User already exists. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/users/me: get: tags: ["Users"] summary: Detalhes do usuário description: Obtém detalhes do usuário autenticado responses: '200': description: User details content: application/json: schema: $ref: "#/components/schemas/User" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/auth/login: post: tags: ["Auth"] summary: Login para obter o token de acesso description: Realiza login para criar e retornar o token de acesso JWT do usuário autenticado requestBody: required: true content: application/x-www-form-urlencoded: schema: type: object properties: username: type: string password: type: string required: - username - password responses: '200': description: Token generated successfully content: application/json: schema: $ref: "#/components/schemas/Token" '401': description: User or password incorrect content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/auth/refresh: post: tags: ["Auth"] summary: Renova access token description: Usa refresh token para gerar novo access token requestBody: required: true content: application/json: schema: type: object properties: refresh_token: type: string example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." required: ["refresh_token"] responses: 200: description: New access token generated content: application/json: schema: $ref: "#/components/schemas/Token" 401: description: Could not validate refresh token /api/v1/books: get: tags: ["Books"] summary: Lista todos os livros description: Lista todos os livros disponíveis na base de dados. responses: '200': description: List of all books content: application/json: schema: type: array items: $ref: "#/components/schemas/Book" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: "Internal Server Error Occurred" content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/books/{id}: parameters: - name: id in: path description: ID do livro a ser detalhado required: true schema: type: integer get: tags: ["Books"] summary: Detalhe de um livro pelo ID description: Retorna detalhes completos de um livro específico pelo ID. responses: '200': description: Book detail content: application/json: schema: $ref: "#/components/schemas/Book" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '404': description: Book with specific ID not found content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/books/search: get: tags: ["Books"] summary: "Busca livros por título e/ou categoria" description: "Retorna uma lista de livros filtrados por título e ou categoria, caso nenhum título ou categoria seja passado retorna uma lista com todos os livros." parameters: - name: title in: query description: Título (ou parte) do livro required: false schema: type: string - name: category in: query description: Nome da categoria required: false schema: type: string responses: '200': description: Book search results content: application/json: schema: type: array items: $ref: "#/components/schemas/Book" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/books/top-rated: get: tags: ["Books"] summary: Lista livros com melhor avaliação description: Retorna uma lista de livros com as melhores avaliações (rating mais alto) parameters: - name: limit in: query description: Número de livros com as avaliações mais altas required: false schema: type: integer default: 10 minimum: 1 example: 10 responses: '200': description: Top-rated book results content: application/json: schema: type: array items: $ref: "#/components/schemas/Book" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/books/price-range: get: tags: ["Books"] summary: "Filtra livros dentro de uma faixa de preço específica." description: "Retorna uma lista filtrada de livros dentro de uma faixa de preço específica que está entre **min** e **max** (inclusivo)" parameters: - name: min in: query description: "Preço mínimo" required: true schema: type: number format: float minimum: 0.0 example: 20.0 - name: max in: query description: "Preço máximo" required: true schema: type: number format: float minimum: 0.0 example: 50.0 responses: '200': description: A list of books within the given price range content: application/json: schema: type: array items: $ref: "#/components/schemas/Book" '400': description: Minimum value must not be greater than maximum value content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/categories: get: tags: ["Categories"] summary: "Lista todas as categorias" description: "Retorna uma lista contendo todas as categorias dos livros disponíveis" responses: '200': description: Category List content: application/json: schema: type: array items: $ref: "#/components/schemas/Category" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/stats/overview: get: tags: ["Stats"] summary: "Estatísticas gerais dos livros" description: "Retorna estatísticas gerais, como número total de livros, preço médio e distribuição de classificação." responses: '200': description: Overview statistics returned successfully content: application/json: schema: $ref: "#/components/schemas/Stats" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/stats/categories: get: tags: ["Stats"] summary: "Obtenha estatísticas por categoria" description: "Retorna estatísticas agrupadas por categoria, incluindo número de livros e preço médio por categoria." responses: '200': description: Category statistics returned successfully content: application/json: schema: type: array items: $ref: "#/components/schemas/CategoryStats" '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Internal Server Error Occurred content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /api/v1/scraping/trigger: post: tags: ["Scraping"] summary: "Aciona manualmente o processo de scraping" responses: '202': description: Scraping started '401': description: Not authenticated content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" '500': description: Error starting scraping content: application/json: schema: $ref: "#/components/schemas/ErrorResponse"