-
-
Notifications
You must be signed in to change notification settings - Fork 487
Add OpenAPI recipe #3148
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Add OpenAPI recipe #3148
Conversation
Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. |
WalkthroughThis change introduces a new Go-based OpenAPI example project. It adds environment configuration, a PostgreSQL database connection layer, a Book model, CRUD handlers for books, HTTP route registration using Fiber and Huma, and comprehensive documentation in a README. The application supports OpenAPI documentation and TypeScript schema generation. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant FiberApp
participant Huma
participant Handlers
participant Database
User->>FiberApp: HTTP Request (e.g., GET /v1/books)
FiberApp->>Huma: Route dispatch
Huma->>Handlers: Call handler (e.g., GetAllBooks)
Handlers->>Database: Query (e.g., books list)
Database-->>Handlers: Query result
Handlers-->>Huma: Response struct
Huma-->>FiberApp: Formatted HTTP response
FiberApp-->>User: API Response
Poem
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (9)
openapi/.env (1)
1-5
: Add missing blank line and consider documentation for production use.The static analysis tool flagged a missing blank line at the end of the file. While the key ordering warnings are not critical, adding proper documentation would help users understand how to configure this for production.
DB_USER= DB_PASSWORD= DB_HOST= DB_NAME= DB_PORT= +
Consider adding comments to guide users:
+# Database connection configuration +# Fill in these values for your environment DB_USER= DB_PASSWORD= DB_HOST= DB_NAME= DB_PORT= +🧰 Tools
🪛 dotenv-linter (3.3.0)
[warning] 2-2: [UnorderedKey] The DB_PASSWORD key should go before the DB_USER key
[warning] 3-3: [UnorderedKey] The DB_HOST key should go before the DB_PASSWORD key
[warning] 4-4: [UnorderedKey] The DB_NAME key should go before the DB_PASSWORD key
[warning] 5-5: [EndingBlankLine] No blank line at the end of the file
[warning] 5-5: [UnorderedKey] The DB_PORT key should go before the DB_USER key
openapi/main.go (1)
13-22
: Consider making the server port configurable.The application structure is well-organized with proper error handling. However, the server port is hardcoded to 3000.
Consider making the port configurable via environment variable:
+import ( + "log" + "os" + + "openapi/database" + "openapi/models" + "openapi/routes" + + _ "github.com/joho/godotenv/autoload" +) func main() { if err := database.Connect(); err != nil { log.Panic("Can't connect database:", err.Error()) } database.DBConn.AutoMigrate(&models.Book{}) + port := os.Getenv("PORT") + if port == "" { + port = "3000" + } + app := routes.New() - log.Fatal(app.Listen(":3000")) + log.Fatal(app.Listen(":" + port)) }Then add
PORT=3000
to the .env file for consistency.openapi/database/connection.go (1)
30-30
: Consider SSL configuration for production environments.The connection string uses
sslmode=disable
, which is acceptable for development but should be reconsidered for production environments.For production deployments, consider using
sslmode=require
or higher security levels. You might want to make this configurable via environment variable:+ sslMode := os.Getenv("DB_SSL_MODE") + if sslMode == "" { + sslMode = "disable" // Default for development + } + - dsn := fmt.Sprintf("user=%s password=%s host=%s dbname=%s port=%d sslmode=disable", user, password, host, db, portInt) + dsn := fmt.Sprintf("user=%s password=%s host=%s dbname=%s port=%d sslmode=%s", user, password, host, db, portInt, sslMode)openapi/routes/routes.go (2)
17-21
: Consider using a more production-ready log format.The current log format uses color codes and a simple date format. For production environments, consider using structured logging or a more standard format that's easier to parse by log aggregation tools.
- app.Use(logger.New(logger.Config{ - Format: "${cyan}[${time}] ${white}${pid} ${red}${status} ${blue}[${method}] ${white}${path}\n", - TimeFormat: "02-Jan-2006", - TimeZone: "UTC", - })) + app.Use(logger.New(logger.Config{ + Format: "[${time}] ${pid} ${status} [${method}] ${path} - ${latency}\n", + TimeFormat: "2006-01-02T15:04:05Z07:00", + TimeZone: "UTC", + }))
29-37
: Clean up or document the commented code.The commented code shows an alternative way to register routes with more OpenAPI metadata. Either remove it if it's not needed or move it to documentation/examples.
If this is meant as an example for users, consider moving it to the README.md file or create a separate example file. If it's no longer needed, remove it to keep the code clean.
openapi/README.md (2)
47-50
: Improve readability by varying sentence beginnings.The static analysis correctly identified repetitive sentence structures. Consider rewording for better flow.
- - OpenAPI 3.1 JSON: `http://localhost:3000/openapi.json`. - - OpenAPI 3.1 YAML: `http://localhost:3000/openapi.yaml`. - - OpenAPI 3.0.3 JSON: `http://localhost:3000/openapi-3.0.json`. - - OpenAPI 3.0.3 YAML: `http://localhost:3000/openapi-3.0.yaml`. + - JSON format (3.1): `http://localhost:3000/openapi.json` + - YAML format (3.1): `http://localhost:3000/openapi.yaml` + - JSON format (3.0.3): `http://localhost:3000/openapi-3.0.json` + - YAML format (3.0.3): `http://localhost:3000/openapi-3.0.yaml`🧰 Tools
🪛 LanguageTool
[style] ~49-~49: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...p://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/open...(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/open...(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
60-60
: Fix article usage.Use "an" instead of "a" before words starting with vowel sounds.
-Here is a minimal example of adding huma to a existing Fiber codebase: +Here is a minimal example of adding huma to an existing Fiber codebase:🧰 Tools
🪛 LanguageTool
[misspelling] ~60-~60: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ... is a minimal example of adding huma to a existing Fiber codebase:`routes...
(EN_A_VS_AN)
openapi/handlers/book.go (2)
37-37
: Consider adding nil check for database connection.The code assumes
database.DBConn
is always available. Adding a nil check would make the handler more robust.func GetAllBooks(ctx context.Context, _ *struct{}) (*GetAllBooksResponse, error) { db := database.DBConn + if db == nil { + return nil, huma.Error500InternalServerError("database connection not available") + }Apply this pattern consistently across all handlers.
92-97
: Consider using atomic update operations.The current approach reads the record first, then updates individual fields. This could lead to race conditions. Consider using a single update operation.
- book.Title = input.Body.Title - book.Author = input.Body.Author - book.Publisher = input.Body.Publisher - if err := db.Save(&book).Error; err != nil { - return nil, err - } + updates := models.Book{ + Title: input.Body.Title, + Author: input.Body.Author, + Publisher: input.Body.Publisher, + } + if err := db.Model(&book).Updates(updates).Error; err != nil { + return nil, err + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
openapi/go.mod
is excluded by!**/*.mod
openapi/go.sum
is excluded by!**/*.sum
,!**/*.sum
📒 Files selected for processing (7)
openapi/.env
(1 hunks)openapi/README.md
(1 hunks)openapi/database/connection.go
(1 hunks)openapi/handlers/book.go
(1 hunks)openapi/main.go
(1 hunks)openapi/models/book.go
(1 hunks)openapi/routes/routes.go
(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
openapi/routes/routes.go (1)
openapi/handlers/book.go (5)
GetAllBooks
(36-44)GetBookByID
(46-59)RegisterBook
(61-76)UpdateBook
(78-100)DeleteBook
(102-118)
openapi/handlers/book.go (3)
openapi/models/book.go (1)
Book
(6-11)openapi/database/connection.go (1)
DBConn
(15-15)gorm-mysql/routes/routes.go (1)
Delete
(60-68)
🪛 dotenv-linter (3.3.0)
openapi/.env
[warning] 2-2: [UnorderedKey] The DB_PASSWORD key should go before the DB_USER key
[warning] 3-3: [UnorderedKey] The DB_HOST key should go before the DB_PASSWORD key
[warning] 4-4: [UnorderedKey] The DB_NAME key should go before the DB_PASSWORD key
[warning] 5-5: [EndingBlankLine] No blank line at the end of the file
[warning] 5-5: [UnorderedKey] The DB_PORT key should go before the DB_USER key
🪛 LanguageTool
openapi/README.md
[style] ~49-~49: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...p://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/open...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/open...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[misspelling] ~60-~60: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ... is a minimal example of adding huma to a existing Fiber codebase:
`routes...
(EN_A_VS_AN)
🔇 Additional comments (2)
openapi/models/book.go (1)
5-11
: LGTM! Well-structured model with good OpenAPI support.The Book struct is well-designed with:
- Proper GORM model embedding
- Clear JSON tags for API serialization
- Example values that will enhance OpenAPI documentation generation
openapi/database/connection.go (1)
41-43
: Connection pool configuration looks appropriate.The connection pool settings (10 idle, 50 max open, 1 hour lifetime) are reasonable defaults for most applications.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (4)
openapi/.env (1)
1-5
: Add a trailing newline for POSIX conformance and clarify lint expectationsEnsure the file ends with a blank line to satisfy common tooling and POSIX standards. The dotenv-linter warnings about key ordering can be safely ignored here since grouping credentials (user/password) separately from connection info (host/name/port) improves readability.
--- a/openapi/.env +++ b/openapi/.env @@ -5,1 +5,2 @@ DB_PORT= +🧰 Tools
🪛 dotenv-linter (3.3.0)
[warning] 2-2: [UnorderedKey] The DB_PASSWORD key should go before the DB_USER key
[warning] 3-3: [UnorderedKey] The DB_HOST key should go before the DB_PASSWORD key
[warning] 4-4: [UnorderedKey] The DB_NAME key should go before the DB_PASSWORD key
[warning] 5-5: [EndingBlankLine] No blank line at the end of the file
[warning] 5-5: [UnorderedKey] The DB_PORT key should go before the DB_USER key
openapi/README.md (3)
13-13
: Grammar: use “was inspired” instead of “got inspired”.
Replace “This project got inspired by the swagger recipe” with “This project was inspired by the swagger recipe.”
60-60
: Use “an” before a vowel sound.
Change “adding huma to a existing Fiber codebase” to “adding huma to an existing Fiber codebase.”🧰 Tools
🪛 LanguageTool
[misspelling] ~60-~60: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ... is a minimal example of adding huma to a existing Fiber codebase:`routes...
(EN_A_VS_AN)
96-107
: Optional: include thenet/http
import in the snippet.
To usehttp.MethodGet
, the example should show importingnet/http
. You may add:import ( "net/http" // …other imports… )This will reduce confusion for readers unaware that
http
comes from the standard library.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
openapi/go.mod
is excluded by!**/*.mod
openapi/go.sum
is excluded by!**/*.sum
,!**/*.sum
📒 Files selected for processing (7)
openapi/.env
(1 hunks)openapi/README.md
(1 hunks)openapi/database/connection.go
(1 hunks)openapi/handlers/book.go
(1 hunks)openapi/main.go
(1 hunks)openapi/models/book.go
(1 hunks)openapi/routes/routes.go
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- openapi/models/book.go
- openapi/main.go
- openapi/routes/routes.go
- openapi/database/connection.go
- openapi/handlers/book.go
🧰 Additional context used
🧠 Learnings (1)
openapi/README.md (1)
Learnt from: sixcolors
PR: gofiber/fiber#3446
File: docs/middleware/logger.md:44-44
Timestamp: 2025-05-13T00:19:16.407Z
Learning: In documentation files for the Fiber framework, code examples are often partial and don't repeat import statements that were shown in earlier examples, focusing instead on demonstrating specific usage patterns.
🪛 dotenv-linter (3.3.0)
openapi/.env
[warning] 2-2: [UnorderedKey] The DB_PASSWORD key should go before the DB_USER key
[warning] 3-3: [UnorderedKey] The DB_HOST key should go before the DB_PASSWORD key
[warning] 4-4: [UnorderedKey] The DB_NAME key should go before the DB_PASSWORD key
[warning] 5-5: [EndingBlankLine] No blank line at the end of the file
[warning] 5-5: [UnorderedKey] The DB_PORT key should go before the DB_USER key
🪛 LanguageTool
openapi/README.md
[style] ~49-~49: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...p://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/open...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/open...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[misspelling] ~60-~60: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ... is a minimal example of adding huma to a existing Fiber codebase:
`routes...
(EN_A_VS_AN)
🔇 Additional comments (8)
openapi/README.md (8)
1-5
: Looks good overall.
The front matter is well-formed and accurately describes the document’s purpose.
23-34
: Setup steps are clear.
Cloning the repo and runninggo mod tidy
is explained correctly.
35-45
: Running the application is straightforward.
Thego run main.go
and docs URL section is concise and accurate.
47-51
: OpenAPI spec URLs are correctly listed.
All four endpoints (JSON/YAML for both 3.1 and 3.0.3) are clearly presented.🧰 Tools
🪛 LanguageTool
[style] ~49-~49: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...p://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/open...(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/open...(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
54-57
: TypeScript schema generation command is accurate.
Thenpx openapi-typescript
invocation is correctly shown.
65-70
: Example imports look appropriate.
Showing the Fiber and Huma imports (with...
for brevity) is consistent with prior recipes.
86-90
: Handler example is clear and correct.
The Huma-enhanced handler signature withcontext.Context
and response struct is accurately demonstrated.
109-114
: References are complete and accurate.
All links to Huma docs and related resources are valid and informative.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
openapi/README.md (2)
47-50
: Reduce repetition in OpenAPI spec bullet list.
The bullets all start with "OpenAPI…", which feels repetitive. Consider grouping by format (JSON vs. YAML) or version, or extracting the common prefix to improve readability.🧰 Tools
🪛 LanguageTool
[style] ~49-~49: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...p://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/open...(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/open...(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
60-60
: Fix grammar: use 'an' before a vowel.
Change “adding huma to a existing Fiber codebase” to “adding Huma to an existing Fiber codebase.”🧰 Tools
🪛 LanguageTool
[misspelling] ~60-~60: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ... is a minimal example of adding huma to a existing Fiber codebase:`routes...
(EN_A_VS_AN)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
README.md
(2 hunks)openapi/README.md
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- README.md
🧰 Additional context used
🧠 Learnings (1)
openapi/README.md (1)
Learnt from: sixcolors
PR: gofiber/fiber#3446
File: docs/middleware/logger.md:44-44
Timestamp: 2025-05-13T00:19:16.407Z
Learning: In documentation files for the Fiber framework, code examples are often partial and don't repeat import statements that were shown in earlier examples, focusing instead on demonstrating specific usage patterns.
🪛 LanguageTool
openapi/README.md
[style] ~49-~49: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...p://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/open...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[style] ~50-~50: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/open...
(ENGLISH_WORD_REPEAT_BEGINNING_RULE)
[misspelling] ~60-~60: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ... is a minimal example of adding huma to a existing Fiber codebase:
`routes...
(EN_A_VS_AN)
This PR Inspired by the existing Swagger recipe, this recipe highlights an alternative approach to API documentation with more flexibility and type safety using Huma.
Summary by CodeRabbit