diff --git a/doc/proposals/2025/gsoc/Application_Abhinandan_Sah_Api_dash_feature_Improvements.md b/doc/proposals/2025/gsoc/Application_Abhinandan_Sah_Api_dash_feature_Improvements.md new file mode 100644 index 00000000..0cb99c08 --- /dev/null +++ b/doc/proposals/2025/gsoc/Application_Abhinandan_Sah_Api_dash_feature_Improvements.md @@ -0,0 +1,99 @@ +# GSoC 2025 Proposal for API Dash + +## Personal Information +1. **Full Name**: Abhinandan Sah +3. **Contact Info**: + - Email: abhinandansah222@gmail.com + - Phone: +91 91553 66612 +6. **Discord Handle**: avi2699 +7. **Home Page**: [Home Page](https://portfolioavi.vercel.app/) +8. **Blog**: [https://medium.com/@abhinandansah222](https://medium.com/@abhinandansah222) +9. **GitHub Profile Link**: [github.com/Abhinandan-Sah](https://github.com/Abhinandan-Sah) +10. **Twitter, LinkedIn, Other Socials**: + - LinkedIn: [linkedin.com/in/abhinandan-sah/](https://linkedin.com/in/abhinandan-sah/) + - Twitter: [https://x.com/I_AbhinandanSah](https://x.com/I_AbhinandanSah) +12. **Time Zone**: IST (Indian Standard Time, UTC+5:30) +13. **Link to Resume**: [Click Me](https://portfolioavi.vercel.app/) + +--- + +## University Info +1. **University Name**: Lovely Professional University +2. **Program Enrolled In**: Bachelor of Technology - Computer Science and Engineering +3. **Year**: Pre-Final Year (based on timeline: 2022–2026) +5. **Expected Graduation Date**: July 2026 + +--- + +## Motivation & Past Experience +1. **Have you worked on or contributed to a FOSS project before?** + Yes, I’ve contributed to open-source projects on GitHub, sharpening my skills in collaborative coding. My profile ([github.com/Abhinandan-Sah](https://github.com/Abhinandan-Sah)) includes **DevConnect** ([github.com/Abhinandan-Sah/DevConnect](https://github.com/Abhinandan-Sah/DevConnect)), which I intend to open-source, showcasing real-world development experience. + +2. **What is your one project/achievement that you are most proud of? Why?** + I take pride in **DevConnect** (Feb 2025 – Mar 2025), a full-stack developer networking platform ([github.com/Abhinandan-Sah/DevConnect](https://github.com/Abhinandan-Sah/DevConnect)). This Tinder-like app for devs features real-time chat, audio/video calls, and a smart matching algorithm. It’s a standout achievement because it integrates complex technologies like Socket.IO and AWS, reflecting my ability to build scalable, interactive solutions. + +3. **What kind of problems or challenges motivate you the most to solve them?** + I’m driven by challenges that improve user experiences, integrate cutting-edge tech (e.g., real-time systems, APIs), and enhance scalability. Creating tools like API Dash or platforms like DevConnect that solve real-world problems fuels my passion. + +4. **Will you be working on GSoC full-time?** + Yes, I’ll dedicate myself full-time to GSoC in the summer of 2025, focusing entirely on API Dash. + +5. **Do you mind regularly syncing up with the project mentors?** + Not at all—I thrive on collaboration and welcome regular mentor sync-ups to ensure alignment and quality. + +6. **What interests you the most about API Dash?** + API Dash’s goal of simplifying API testing aligns with my love for developer tools. Its Dart/Flutter stack excites me as a learning opportunity, and its open-source ethos matches my experience with projects like DevConnect. + +7. **Can you mention some areas where the project can be improved?** + From the issue tracker, I’d focus on: + - JSON body enhancements (syntax highlighting, validation, beautification - #581, #582, #583). + - Environment variable support in request bodies (#590–593). + - A richer GraphQL editor with schema inspection and variable support. + +--- + +## Project Proposal Information + +### 1. Proposal Title +**Enhancing API Dash: JSON Body Improvements and Environment Variable Support** + +### 2. Abstract +This project will enrich API Dash by adding JSON request body syntax highlighting, validation, beautification, and environment variable support. These upgrades will provide developers with real-time JSON feedback, auto-formatting, and dynamic variable integration, boosting usability and efficiency using Dart and Flutter. + +### 3. Detailed Description +API Dash’s request body editor can become a more powerful tool with: +- **Syntax Highlighting**: Color-coded JSON for enhanced readability. +- **Validation**: Real-time syntax error detection with UI feedback. +- **Beautification**: Auto and manual JSON formatting with proper indentation. +- **Environment Variable Support**: Dynamic variables in JSON, text, and form bodies, linked to API Dash’s environment system. + +### 4. Weekly Timeline +- **Week 1**: Explore API Dash codebase, set up dev environment, design JSON editor features. +- **Week 2**: Implement JSON syntax highlighting with Flutter text widgets. +- **Week 3**: Add real-time JSON validation with error messaging. +- **Week 4**: Build beautification feature (auto/manual modes). +- **Week 5**: Integrate environment variables in JSON request bodies. +- **Week 6**: Extend variable support to text and form bodies (#591, #593). +- **Week 7**: Develop unit and widget tests for all features. +- **Week 8**: Polish UI, fix bugs, and document code. +- **Week 9**: Buffer week for testing, mentor feedback, and refinements. +- **Week 10**: Finalize PR, create demo, and submit documentation. + +**Total Hours**: ~175 hours (Medium difficulty) + +--- + +## Skills & Fit +- **Technical Skills**: Dart, Flutter (to learn), React, Redux, Node.js, Express, MongoDB, JWT, Socket.IO, TailwindCSS, AWS (EC2, SES), Git, REST APIs. +- **Experience**: + - **DevConnect**: Full-stack app with real-time chat, audio/video calls, and AWS deployment. + - **Gptflix**: AI-driven movie recommendation site with API integrations. + - Training at Gokboru PVT Limited: Optimized web apps with React and Tailwind. +- **Soft Skills**: Problem-solving, teamwork, adaptability—demonstrated in hackathons and collaborative projects. + +--- + +## Additional Notes +- My work on DevConnect’s real-time systems and API integrations fuels my enthusiasm to enhance API Dash’s developer-friendly features! + +--- diff --git a/doc/proposals/2025/gsoc/Application_Ayushman_Pal_API_Explorer.md b/doc/proposals/2025/gsoc/Application_Ayushman_Pal_API_Explorer.md new file mode 100644 index 00000000..07c95d4b --- /dev/null +++ b/doc/proposals/2025/gsoc/Application_Ayushman_Pal_API_Explorer.md @@ -0,0 +1,137 @@ +### About + +1. Full Name: Ayushman Pal +2. Contact info (email, phone, etc.): + - Email: payushman72@gmail.com + - Phone: +91-8755087453 +3. Discord handle: mr_robot_016 +4. Home page (if any): https://github.com/WannaCry016 +5. GitHub profile link: https://github.com/WannaCry016 +6. LinkedIn: https://www.linkedin.com/in/ayushman-pal-392323254/ +7. Time zone: Indian Standard Time +8. Link to a resume (PDF, publicly accessible via link and not behind any login-wall): + https://drive.google.com/file/d/18zCj5FUC4uffh8LmrSQft90mIry6iXDY/view + +### University Info + +1. University name: Indian Institute of Technology, Madras +2. Program you are enrolled in (Degree & Major/Minor): BTech, Chemical Engineering +3. Year: 3rd Year +4. Expected graduation date: 08/2026 + +### Motivation & Past Experience + +1. **Have you worked on or contributed to a FOSS project before? Can you attach repo links or relevant PRs?** + Yes, I have contributed to FOSS projects: + - https://github.com/foss42/apidash/pull/684: Fixed UI alignment issues to improve visual consistency across the app. + - https://github.com/foss42/apidash/pull/725: Made enhancements to the UI. + - https://github.com/foss42/apidash/pull/794: Replaced the underlying HTTP client from `http` to `dio`, enabling better error handling and extensibility. + +2. **What is your one project/achievement that you are most proud of? Why?** + One project I’m proud of is the OEMS (Order Execution Management System), which I built in C++. It was a challenging backend system involving low-level networking, WebSockets, multi-threading, and real-time data streaming. I learned a lot about performance optimization and robust backend design through this project. + +3. **What kind of problems or challenges motivate you the most to solve them?** + I’m most motivated by problems that involve developer experience, performance bottlenecks, and clean abstractions. I enjoy creating tools that improve developer workflows, exploring AI-powered enhancements, and optimizing real-time systems. + +4. **Will you be working on GSoC full-time? In case not, what will you be studying or working on while working on the project?** + Yes, I plan to dedicate myself full-time to GSoC and ensure consistent progress throughout the coding period. + +5. **Do you mind regularly syncing up with the project mentors?** + Not at all — I value regular sync-ups and feedback to stay aligned with project goals and to produce high-quality work. + +6. **What interests you the most about API Dash?** + API Dash is a clean, elegant tool built with a strong focus on developer productivity. I love its minimalist UI, open-source ethos, and the potential it has to become a one-stop tool for API testing with AI-enhanced features. + +7. **Can you mention some areas where the project can be improved?** + - Adding support for protocols beyond REST/GraphQL (like gRPC or WebSockets). + - Making the API explorer more interactive and intuitive. + - Providing a plugin system or richer AI assistance during request creation. + + +### Project Proposal Information + +**Proposal Title**: API Explorer: A Curated & Customizable API Library for API Dash + +**Abstract**: +API Dash lacks a built-in feature for discovering, managing, and importing publicly available APIs efficiently. Developers often manually set up API requests, which leads to repetitive, error-prone setups and increases onboarding time. + +**Solution**: +The API Explorer aims to address this by allowing developers to browse, save, import, and generate pre-filled API requests using various formats (OpenAPI, Postman, etc.). Key features include: + +- Discover curated API templates categorized by domain (e.g., Finance, AI, Weather). +- Upload OpenAPI/Postman/HTML documentation files and auto-generate corresponding API templates. +- Save custom user-defined API templates for future use. +- View endpoint metadata (parameters, authentication methods, response samples). +- AI-assisted filling of incomplete documentation and auto-suggesting missing fields. +- Convert an existing API request into a reusable template via one-click export. +- Seamless integration into the Request Tab, allowing quick import and testing. +- Future extensibility with plugin support or integrations with public API marketplaces. + +**Detailed Description**: +The API Explorer will be developed as a modular and extensible component within API Dash. It will include a frontend section (likely under a new tab) to explore API templates and a backend engine to parse uploaded OpenAPI specs or Postman collections. The templates will be stored either locally or optionally synced with GitHub gists/cloud. Each template will display metadata like endpoint name, method, headers, body format, query/path parameters, and examples. There will be options to import templates directly into the Request Tab and export request setups as shareable JSON templates. AI features will use LLM-powered completions (possibly via an optional local/integrated model or OpenAI plugin) to suggest missing headers, descriptions, or parameter values. + +Users can also tag and organize their saved templates, making this not just a tool for immediate use, but also a personal API library over time. + + +### Weekly Timeline + +**Community Bonding Period** +- Interact with mentors, finalize the API Explorer UX and core scope. +- Review existing API Dash codebase, especially how requests are stored/imported/exported. +- Research supported import formats (OpenAPI 3.0+, Postman, cURL, etc.). +- Set up environment for development and testing. + +**Week 1: Core Architecture Setup** +- Create skeleton UI for API Explorer tab/component. +- Set up JSON template schema (compatible with OpenAPI/Postman). +- Set up file upload mechanism and create file parser modules for OpenAPI and Postman. +- Display parsed endpoints in a basic list view. + + +**Week 2: Template Viewer and Import Integration** +- Build full UI to list, browse, and preview parsed APIs. +- Add “Import to Request Tab” functionality for pre-filled API calls. +- Support filtering APIs by tags, domain, and authentication type. +- Add local storage/database support for saving templates. + + +**Week 3: User-defined Templates & Exporting** +- Add feature to save a request as a template from the Request Tab. +- Enable exporting these templates as JSON for backup or sharing. +- UI for managing saved templates (edit, rename, delete, categorize). +- Add visual indicators for required/optional fields in templates. + + +**Week 4: Advanced Parsing + AI Enhancements Phase 1** +- Add support for additional fields like examples, descriptions, and status codes. +- Integrate a basic AI module to auto-fill missing descriptions (OpenAI/local LLM). +- Parse authentication metadata from OpenAPI/Postman and show in UI. +- Test edge cases of complex nested parameters. + + +**Week 5: AI Enhancements Phase 2 + Bulk Import** +- Add AI-assisted suggestions for filling headers, auth, or query values. +- Enable uploading zip files with multiple specs for batch import. +- Improve UI for better UX – tabs for Preview, Metadata, Raw JSON, etc. +- Add light/dark mode compatibility and responsive design. + + +**Week 6: Template Organization & Tagging System** +- Add tagging and categorization system for user templates. +- Add search and filter options in the API Explorer. +- Implement pagination or lazy loading for large collections. +- Performance optimizations. + + +**Week 7: Testing, Validation, and Documentation** +- Write unit/integration tests for parser modules and UI components. +- Validate edge cases in OpenAPI/Postman import (complex nesting, arrays, etc.). +- Write user documentation for API Explorer. +- Create demo templates for popular APIs (e.g., OpenAI, Stripe, Twilio). + + +**Week 8: Final Review & Polishing** +- Bug fixing, refactoring, and code cleanup. +- Final UX refinements based on mentor feedback. +- Ensure the final PR is merge-ready. +- Prepare GSoC final report and a recorded demo video. diff --git a/doc/proposals/2025/gsoc/Application_Dheeraj_Krishna_DashBot.md b/doc/proposals/2025/gsoc/Application_Dheeraj_Krishna_DashBot.md new file mode 100644 index 00000000..7fa3b540 --- /dev/null +++ b/doc/proposals/2025/gsoc/Application_Dheeraj_Krishna_DashBot.md @@ -0,0 +1,166 @@ +# GSoC 2025 Proposal: DashBot – AI Assistant for API Dash (#621) and New Feature Requests + +## Personal Information + +- **Name:** Dheeraj Krishna Gedda +- **Email:** dheerajdheeru64@gmail.com +- **Resume:** [Drive Link](https://drive.google.com/file/d/1Ug2jdta9M9YdmsP6Uik62ifLqzdwf0KB/view?usp=sharing) +- **GitHub:** [dheerxj](https://github.com/dheerxj) +- **LinkedIn:** [linkedin.com/in/dheeraj](https://www.linkedin.com/in/dheeraj-krishna-115499238/) +- **University:** Institute of Aeronautical Engineering +- **Degree Program:** B.Tech in Computer Science Engineering (AI and ML) +- **Current Year:** 4th Year + +--- + +## 🧠 Synopsis + +**Project:** DashBot – AI Assistant for API Dash (#621) +DashBot is an AI-powered assistant for API Dash, designed to assist developers in debugging, testing, documenting, and visualizing APIs using natural language. It will support modular plug-ins, LLM benchmarking, and developer productivity tools — transforming API Dash into a smarter, AI-first platform. + +--- + +## 🌍 Benefits to the Community + +- Simplifies API debugging and understanding +- Accelerates code generation and documentation tasks +- Helps beginners write and understand test cases +- Adds smarter productivity features (e.g., numbering, zoom, 2D scroll) +- Enables LLM benchmarking, valuable for enterprise adoption +- Makes API Dash a more developer-friendly tool + +--- + +## ✅ Deliverables + +- [ ] Feature of Numbering and 2D scrolling for authentic view of response +- [ ] Response explanation and discrepancy identification +- [ ] Request debugging using status codes and error traces +- [ ] API documentation generator (from OpenAPI specs or raw endpoints) +- [ ] API test generation using LLMs +- [ ] Visualization module for response data +- [ ] Frontend code generation (Dart-Flutter) +- [ ] Benchmark evaluation module for different LLMs + +--- + +## 📅 Timeline (175 Hours) + +| Week(s) | Dates | Phase | Hours | Tasks | +|---------|--------------------|--------------------------|--------|------------------------------------------------------------------------| +| 1–4 | May 20 – June 16 | Community Bonding | 10 | Engage with mentors and community, finalize specs, understand codebase | +| 5 | June 17 – June 23 | Phase 1 Begins | 15 | Set up project structure, basic utilities | +| 6–7 | June 24 – July 7 | Response Explanation | 25 | Implement response explanation and discrepancy detection | +| 8 | July 8 – July 14 | Debugging Module | 20 | Implement debugging support for status codes and errors | +| | | Testing + Docs | 5 | Add unit tests and documentation for features | +| 9 | July 15 | Midterm Evaluation | — | Submit midterm eval, share demo and progress | +| 10 | July 16 – July 22 | Flutter Code Generator | 20 | Build API integration generator for Flutter | +| 11 | July 23 – July 29 | Test Case Generation | 15 | Create test cases from API data | +| 12 | July 30 – Aug 5 | Visualization Support | 20 | Implement customizable charts & plots | +| 13 | Aug 6 – Aug 12 | 📄 Documentation | 10 | Write docs for all new modules | +| 14 | Aug 13 – Aug 19 | ✅ Final Submission | 35 | Benchmark LLMs, polish code, testing, final report + blog + PRs | + +--- + +## ⚙️ Implementation Plan & Workflow + +### 🛠️ High-Level Architecture + +DashBot is a modular system that includes: +- Natural Language Understanding (NLU) +- Intent classification +- Task execution modules (debug, test, doc, viz, codegen) +- LLM benchmarking engine +- Customizable frontend options for code and visualization + +--- + +### 🔄 Workflow Steps + +1. **User Input Interface** + - Developer types natural language queries + - Select LLM (OpenAI, Llama3, Mistral, etc.) + - Select output format (text, chart, Flutter code, etc.) + +2. **Intent Classification** + - Classify query: Is it about debugging, generating docs, or something else? + - Route to the right module + +3. **Module Execution** + - Debug Module → Analyze response, error codes + - CodeGen Module → Generate integration code (Flutter/Dart) + - TestGen Module → Generate test cases based on request/response + - DocGen Module → Generate OpenAPI-style docs + - Viz Module → Build dynamic charts from response data + +4. **LLM Orchestration** + - Prompt-Template system to guide LLM output + - Benchmark multiple LLMs (accuracy/time/consistency) + - YAML-based log format for outputs + +5. **Response UI Layer** + - Frontend displays code, charts, test cases + - 2D scroll, numbering, and zoom support for large outputs + +--- + +## 👨‍💻 Technical Approach + +- Use OpenAI, Claude, Mistral, LLaMA 3 via API +- LangChain or custom Python logic for modular prompt routing +- Code generation via templates + OpenAPI + Flutter +- Chart rendering via Plotly.js or ECharts +- Test generation with schema-based prompt inference +- YAML-based benchmarking logs (response accuracy, latency, etc.) + +--- + +## 🙋 Why Me? + +- 4x National Hackathon Winner (T-Hub, Hackfest, etc.) +- Experience in AI + Flutter + Firebase + Python +- Built production-level apps listed on Play Store +- Built NLP bots with Sentiment/NER + Telegram bots +- Actively contribute to open-source and issue discussions + +--- + +## 🛠️ Prior Contributions + +- PR #805: Fix for horizontal scroll bug (#672) +- PR for Feature #675: 2D scrolling feature +- Discussions around better visualization and LLM integration +- UI/UX suggestions to improve API Dash code experience + +--- + +## 🚀 Post-GSoC Plans + +I plan to stay active in API Dash even after GSoC by: +- Maintaining and improving DashBot +- Adding chatbot-like interaction UX +- Improving LLM benchmarking UI +- Assisting new contributors + +--- + +## 📂 Additional Links + +- **Past Projects:** + - [Chatbot-NLP](https://github.com/dheerxj/chatbot-nlp): Rule-based + NER + Sentiment Chatbot + - [Building Guardian](https://github.com/dheerxj/building-guardian): Full-stack building management app (Flutter + Firebase) + +--- + +## 🔖 Tags + +`Flutter` `Python` `AI` `LLM` `Open Source` `GSoC 2025` `API Dash` `DashBot` + +--- + +## 🧭 Flowchart: DashBot Development Process +![image](https://github.com/user-attachments/assets/e820ccb1-d356-4bc4-8237-ff2c20fb4fb8) + + +![image](https://github.com/user-attachments/assets/d3fe38a4-981d-4a0b-94f8-14896336adf0) + diff --git a/doc/proposals/2025/gsoc/Application_Kushagra_Migration_Dio_API_Testing.md b/doc/proposals/2025/gsoc/Application_Kushagra_Migration_Dio_API_Testing.md new file mode 100644 index 00000000..78bc80ec --- /dev/null +++ b/doc/proposals/2025/gsoc/Application_Kushagra_Migration_Dio_API_Testing.md @@ -0,0 +1,344 @@ +# **Personal Information** + + **Full Name:** Kushagra Dwivedi + + **Contact Information:** + +**Phone:** \+91 9953739392 +**LinkedIn:** [https://www.linkedin.com/in/kushagradwi/](https://www.linkedin.com/in/kushagradwi/) +**GitHub:** [https://github.com/kushagradwi](https://github.com/kushagradwi) + +**Time Zone:** GMT+5:30 + **Resume Link:** [Kush Resume 2025.pdf](https://drive.google.com/file/d/1MBwwEBDIX8gvIRCl3g08f9umrbp8mj_z/view?usp=drive_link) + +--- + +# **University Information** + +**University Name:** JSSATEN + **Program:** B.Tech in Electrical and Electronics Engineering (E.E.E.) + **Year:** 2016-2020 + **Graduation Date:** 2020 + +--- + +# + +# + +# + +# + +# + +# **Motivation & Past Experience** + +1. **Have you worked on or contributed to a FOSS project before?** + Yes, I have submitted a PR. + +2. **What is your one project/achievement that you are most proud of? Why?** + I cleared the Infosys Power Programmer Exam on my first attempt with a perfect 100% score. It was a significant turning point in my career, especially since I came from a non-computer science background and started as a support engineer with limited coding experience. Preparing for the exam required a lot of hard work and dedication, but it also helped me realize my passion for coding and software development. With an acceptance rate of less than 5%, successfully passing the exam gave me a sense of accomplishment and boosted my confidence to pursue a career in software development. + +3. **What kind of problems or challenges motivate you the most to solve them?** + I enjoy working with complex systems and figuring out the most efficient solutions. I’m always curious about new technologies and frameworks – lately, I’ve been getting into Flutter – because I want to build a more well-rounded understanding of software development. What really gets me excited, though, are backend challenges, especially when it comes to scaling and designing robust architectures. + +4. **Will you be working on GSoC full-time?** + I am currently a full-time employee at a firm called Tredence, but my working hours are flexible. I am quite passionate about this program, and therefore I will be able to dedicate 3-4 hours on weekdays and up to 10-12 hours on weekends. + +5. **Do you mind regularly syncing up with the project mentors?** + Regularly syncing up with the project mentors is perfectly fine with me. Any form of digital communication works for me. I can also ensure transparency in my work by updating a shared public progress document that shows the mentors exactly how much progress has been made and provides resources for future documentation of the feature. + +6. **What interests you the most about API Dash?** + I am really impressed by how simple and straightforward API Dash is. I think the implementation is very intuitive and uncomplicated, which is great for new developers and really gravitates me towards choosing to work on it. The user-friendly interface makes it easy to work with APIs, which is especially valuable when managing and testing API requests efficiently. It’s a tool that genuinely streamlines the process without overwhelming the user with complexity, and I believe it will make a significant impact once it becomes more mature. + +7. **Can you mention some areas where the project can be improved?** + I believe it would really help to move away from using the `http` library. I was looking into this issue on GitHub ([issue \#630](https://github.com/foss42/apidash/issues/630)), and I found out that the current API testing setup heavily relies on the Dart `http` library. The problem with this library is that it automatically adds `charset=utf-8` to the `Content-Type` header. This can be a big issue when interacting with APIs that specifically reject headers with that charset, causing compatibility problems and unexpected errors. + What’s even more frustrating is that the `http` package doesn’t let us override this behavior. It’s been a long-standing problem—people have been requesting a fix or an option to disable this since mid-2018. But the maintainers have been hesitant to make any changes because a lot of existing applications depend on it working this way, and changing it could potentially break them. + After researching a bit more, I realized that Dio could be a way better choice. It’s just more powerful and flexible. With Dio, we get way more control over headers, so we wouldn’t have to worry about that annoying charset issue. Plus, it has some other really useful features, like interceptors, better error handling, and built-in support for things like file uploading and downloading. It’s becoming more popular in other projects too, which makes me think that switching to Dio could make the project more robust and future-proof. + + +# **Migration to ‘Dio’ and Extending API Testing Support for \- WebSocket, SSE, MQTT & gRPC** + +**Abstract: A brief summary about the problem that you will be tackling & how.** + +The current API testing setup primarily relies on the Dart http library, which has inherent limitations, especially regarding the automatic addition of the **charset=utf-8** parameter to the **Content-Type header**. This behavior often causes issues when interacting with APIs that explicitly reject such headers, leading to compatibility challenges and unexpected errors. Additionally, **Dio is more powerful and offers greater control over headers, making it a more suitable choice for API testing, and there is increasing adaptation in other projects. In parallel, the testing framework currently lacks support for WebSocket, Server-Sent Events (SSE), MQTT, and gRPC—protocols vital for modern**, real-time applications in IoT, financial markets, and distributed microservices. Migrating to Dio opens the door to these capabilities. This proposal details the step-by-step transition from http to Dio, ensuring backward compatibility while enhancing the project to include streamlined testing and code-generation for real-time protocols. By the end of the project, developers will be able to test traditional REST APIs alongside bi-directional streams (WebSocket), one-way server push (SSE), publish-subscribe models (MQTT), and high-performance RPC (gRPC with Protocol Buffers). + +**Detailed Description** + + This section explores: + +* Current Challenges and Criticisms of http + + * Proposed Migration Plan to Dio + + * Extension to Real-Time Protocols (WebSocket, SSE, MQTT, and gRPC) + + * How gRPC Relies on Protocol Buffers + + **Current Challenges with http** + + **Limited Control Over Requests** + The major criticism is that the http package forcibly appends charset=utf-8 to the Content-Type header and does not allow overriding it—hindering developers who need exact MIME types (e.g., strict application/json without the charset). Despite community requests since mid-2018 to fix or remove this behavior, the maintainers have been reluctant because a large number of applications depend on that exact behavior and might break if it changes. + + **No Built-In Interceptors & Error Handling** + Out of the box, http does not provide a clean way to intercept requests or responses for logging, retries, or token refresh. Developers must manually check status codes and customize each request, resulting in repetitive code. + + **No Real-Time Protocol Support** + While http suffices for basic REST calls, it lacks straightforward features for bi-directional messaging (WebSocket), one-way streaming (SSE), or publish-subscribe (MQTT)—capabilities crucial to modern applications and IoT devices. + + **Limited Flexibility for Advanced Use Cases** + The library focuses on simple request/response functionality. Features like dynamic cancellation tokens, sophisticated error transformations, or code injection via interceptors typically require external wrappers or significant manual effort, making the development experience cumbersome for complex scenarios. + + —------------------------------------------------------------------------------------------------------ + + + **Why Dio?** + + **Flexibility & Control** + + * Developers can freely modify request headers, query parameters, and options—enabling fine-grained control over network requests. + + * Timeouts, response parsing, and other advanced configurations are managed centrally in a single Dio instance. + + **Future Protocol Support** + + * Dio’s roadmap outlines improved integration for WebSocket, SSE, and other streaming mechanisms. + + * This makes it significantly more conducive to real-time application requirements than the http package, which lacks built-in features for such protocols. + + **Interceptors** + + * Request Interceptors allow insertion of auth tokens, logging, or dynamic headers without manually modifying each request. + + * Response Interceptors unify error handling, promoting consistent reporting and data transformations across the entire codebase. + + **Error Handling & Cancellation** + + * Cancellation Tokens enable a robust approach to abort in-flight requests, especially useful for mobile or large-scale apps where some requests may become stale. + + * Dio automatically throws exceptions for non-2xx status codes, reducing repetitive boilerplate by consolidating error management in a single, consistent pathway. + +—----------------------------------------------------------------------------------------------------------------- + +**Proposed Migration Plan** + + We will transition all existing networking code from http to Dio while preserving backward compatibility where possible. Below are the primary steps: + + **Centralized Dio Client** + +* Instantiate a single Dio object configured with interceptors for logging, custom headers, and error handling. + + * This singleton ensures consistent behaviors—like timeout settings, authentication tokens, or debug logs—across the entire codebase. + + **Refactor http Calls to Dio** + + * Replace calls to http.get/post/etc. with dio.get/post/etc., mirroring existing endpoints and payloads. + + * Adjust error handling to align with Dio’s exception-driven approach, ensuring a user-friendly experience. + + **Interceptors & Enhanced Error Handling** + + * Implement a global request interceptor to manage authentication tokens, logging, or dynamic headers. + + * A global response interceptor can standardize how we manage status codes (e.g., showing an alert for 401), parse JSON, or log relevant data for debugging. + + **Testing & Validation** + + * Conduct thorough regression tests to confirm existing features—like file uploads and custom request flows—operate correctly under Dio. + + * Validate that any APIs affected by previous request constraints now work smoothly with enhanced control over headers and timeouts. + +**—----------------------------------------------------------------------------------------------** + +**Real-Time Protocol Support** + + Once Dio is integrated, we can seamlessly integrate WebSocket, SSE, MQTT, and gRPC: + + **Core Protocol Handling Design** + At the core, we will design a Protocol Handler abstraction to encapsulate logic for each new protocol. Each protocol (WebSocket, SSE, MQTT, gRPC) will implement a common interface (e.g., a Dart abstract class) that defines: + +* connect() / disconnect() + + * send() (if applicable) + + * receive() or a Stream for incoming data + + This clean separation of concerns allows: + + * **Extensibility:** Adding a new protocol (e.g., AMQP or GraphQL Subscriptions) later just means writing another handler class. + + * **Generic UI Interactions:** A Riverpod provider could hold a ConnectionManager referencing a WebSocketHandler, MQTTHandler, etc., depending on the request type. + + Where possible, we will leverage well-tested Dart packages for each protocol to avoid reinventing the wheel: + + * **WebSocket:** Use dart:io’s built-in WebSocket (for desktop/mobile). It provides a Stream for incoming messages and a WebSocket.add() method for sending. + + * **SSE:** Rely on Dio for making a streaming GET request with `Accept: text/event-stream` headers, then parse incoming data as Server-Sent Events. + + * **MQTT:** Integrate an existing Dart MQTT client library (e.g., mqtt\_client), which supports connecting, subscribing, and publishing to a broker. + + * **gRPC:** Use the official grpc Dart package (package:grpc). We’ll handle .proto definitions either through precompiled stubs or server reflection. + + All protocol handlers will reside in API Dash’s core library, decoupled from the UI. Each will provide: + + * A Stream of events/messages (for SSE, MQTT, or a listening WebSocket). + + * State variables for connection status (connected, disconnected, error, etc.). + + By using an event-driven approach, the handlers can push updates to the UI layer via Riverpod providers or controllers. + + **Integration with Flutter & Riverpod** + Flutter supplies the reactive UI framework. Riverpod manages and provides global state across the application. The plan: + + * **State Representation** + + * Connection Status: An enum for each protocol (connecting, connected, disconnected, error). + + * Streams of Messages: For protocols that yield ongoing data (WebSocket, SSE, MQTT, gRPC streaming). Riverpod’s StreamProvider can watch the handler’s Stream and rebuild the UI when new data arrives. + + * Form Inputs: For request parameters (like MQTT topic, SSE URL, gRPC method), we can use StateProvider or Notifier classes to keep track. + + * **UI Binding** + + * The Flutter UI will consume these providers. For instance, a Consumer widget listens to the connection status provider to display “Connected” or “Disconnected.” + + * Another Consumer might watch the message stream to append new messages to a scrollable log in real time. + + * **Connection Lifecycle Management** + + * Using Riverpod’s disposal mechanisms (autoDispose), we ensure that if a user closes a request tab or navigates away, the handler is properly closed (e.g., WebSocket or MQTT disconnect). + + * If the user returns, we can reconnect automatically or keep the existing connection active, depending on user preference. + + * **Error Propagation** + + * If any error occurs (e.g., SSE parse error, MQTT broker failure), the handler catches it, updates an error state, and the UI can display a user-friendly message (snackbar, banner, or log). + + * **Flutter Platform Considerations** + + * WebSocket from dart:io works on mobile/desktop. On web, we might use dart:html instead, but API Dash typically targets desktop/mobile environments. + + * MQTT and gRPC are pure Dart, so they should run across platforms without extra platform channels. + +—---------------------------------------------------------------------------------------------------------------- + +**Protocol-Specific Implementation Details** + + While the architecture is unified, each protocol needs specific handling. + + **WebSocket Support** + +* **UI/UX**: A “WebSocket Request” option in the UI. The user enters a wss:// URL, optional subprotocols, then presses “Connect”. An input field lets them send messages, and all inbound messages appear in a log. + + * **Connection**: We use WebSocket.connect() under the hood, track connection status in a provider. On success, status becomes connected; on error, we revert to disconnected and inform the user. + + * **Messaging**: The handler’s sendMessage() method transmits user-provided text (or binary, if we add that). Inbound messages arrive via a Dart Stream. We’ll categorize them as “Server” vs. “Client” messages for clarity in the log. + + * **Closing**: A “Disconnect” button stops the socket, or if the server closes it, we detect the done event and update status. + + * **Code Generation**: After testing, we generate example code in Node.js (using ws or Socket.IO), Python (websockets), or Go (gorilla/websocket) for easy integration. + + **Server-Sent Events (SSE) Support** + + * **UI/UX**: A “Server-Sent Events (SSE) Request” option. The user enters a URL, and we start reading the stream via Dio with headers like Accept: text/event-stream. There’s no “Send” here, as SSE is one-way from server to client. + + * **Implementation**: Dio will open a persistent HTTP connection. As lines come in, we parse them into SSE events. If the connection drops unexpectedly, we can attempt reconnection (per SSE guidelines) or let the user manually reconnect. + + * **Error Handling**: If the endpoint isn’t actually SSE or returns a non-2xx code, we catch and display an error. Malformed events still show raw data for debugging. + + * **Code Generation**: Snippets might include `curl -N `, JavaScript’s `EventSource`, or a Python approach with streaming requests. + + **MQTT Support** + + * **UI/UX**: A “MQTT Client” section. Users configure broker URL (tcp:// or ws://), port, credentials if needed, and a client ID. They can then subscribe to topics and publish messages. + + * **Connection**: The mqtt\_client library handles connecting and orchestrating keep-alive pings. On connect, status changes to connected. Subscriptions are acknowledged by the broker (CONNACK), which we track. + + * **Messages**: Inbound messages are fed to the UI with topic labels. We store them in a provider for easy display. Outbound publishing is also logged for clarity. + + * **Edge Cases**: We handle clean disconnects if the user logs off or if the network fails, in which case we can optionally reconnect. + + * **Code Generation**: Provide snippet templates in Python (paho-mqtt), Node.js (mqtt), or even C++ for IoT boards, reflecting the tested topics and broker settings. + + + + + **gRPC Support** + + * **UI/UX**: A “gRPC Request” type with an interface to select a service method, enter request data, and see unary/streaming responses. Reflection-enabled servers can auto-populate method definitions; otherwise, we require .proto imports. + + * **Service Definition Handling**: We can compile .proto files offline or, if reflection is supported, query the server dynamically to build a method list. + + * **Implementation**: We create a ClientChannel with optional TLS. Each call is either a simple unary (request → response) or a streaming call (server-streaming or bidirectional). The UI shows inbound messages in real-time. + + * **Authentication & Metadata**: For many gRPC services, we set custom metadata (like tokens) or use TLS for encryption. We also handle advanced errors like UNAUTHENTICATED, NOT\_FOUND, etc. + + * **Code Generation**: Show sample stubs in Python, Go, or Java. We assume the user has the matching .proto in those languages. + +**UI/UX Considerations** + +* **Discoverability**: The user can pick from HTTP, GraphQL, WebSocket, SSE, MQTT, or gRPC in a dropdown. Each protocol’s request panel is tailored to its needs. + + * **Consistency**: Maintain the same look and feel across protocols—request config on the left, response/log area on the right. Possibly add features like “clear messages” or “pause auto scroll” in the log. + + * **State Persistence**: We may keep a connection open if the user only switches tabs. This is done via Riverpod’s providers, allowing multiple concurrent real-time connections if desired. + + * **Performance**: Large message volumes can slow the UI. We’ll impose sensible limits (like truncating after 1,000 messages) or using list virtualization so the app remains responsive. + +**Error Handling and Extensibility** + +* **Exception Safety**: All network operations catch exceptions. Protocol parse errors or server disconnects update an error provider, which the UI displays non-intrusively. + + * **Open-Closed Principle**: Separate handler classes \+ an abstract interface make the system easy to extend (e.g., adding Socket.IO or AMQP without major refactoring). + + * **Documentation**: Thoroughly comment the code and handler interfaces so maintainers can evolve the system post-GSoC. + + * **Reusing Components**: For example, code generation builds on API Dash’s existing framework for snippet generation, simply adding new templates for each protocol. + +**Testing Strategy** + +* **Unit Tests** + Each protocol handler is tested with realistic scenarios. For SSE, feed mock event lines. For MQTT, connect to a test broker or a local mock. For WebSocket, use an echo server. For gRPC, spin up a local server or connect to public test services. + + * **Integration Tests (Widget Tests)** + Simulate user flows in Flutter’s testing environment (e.g., the user enters a WebSocket URL, hits connect, sees messages). + + * **Manual & Cross-Platform Testing** + Validate that code runs smoothly on multiple platforms (Windows, Linux, Android). + Use known public endpoints (e.g., wss://echo.websocket.org, test.mosquitto.org for MQTT) to confirm real-world stability. + + * **Performance & Load Testing** + Monitor CPU/memory usage with large volumes of messages in SSE/WebSocket. Ensure Riverpod’s autoDispose or state teardown prevents memory leaks. + + * **User Feedback & Iteration** + Share early builds or screenshots with mentors and the API Dash community, collecting UI/UX feedback to refine features (e.g., advanced filtering for MQTT logs, toggles for gRPC streaming options). + + **Summary** + + By migrating to Dio (for SSE streaming and advanced request management) and adopting specialized libraries for WebSocket, MQTT, and gRPC, we establish a unified architecture within API Dash. This includes: + + * A Protocol Handler interface for consistent handling of connection, messaging, and error states. + + * Riverpod for reactive state management, enabling a smooth UI that automatically updates with real-time data. + + * Thorough testing and documentation, ensuring each protocol is robust, extensible, and well understood. + + **Result**: API Dash will offer first-class support for real-time protocols—making it a one-stop solution for developers who need to test, debug, and generate code for anything from simple REST endpoints to advanced streaming or RPC services. This positions API Dash competitively among modern API clients, while also preserving the open-source spirit and a flexible architecture for future expansions. + +**Timeframe** + +| Phase | Timeframe | Objectives & Tasks | +| ----- | ----- | ----- | +| | | | +| **Community Bonding & Planning** | Pre-coding (Weeks \-1 to 0\) | \- Review API Dash architecture and current usage of http. \- Discuss approach with mentors. \- Research libraries for WebSocket, SSE, MQTT, gRPC. \- Draft final design doc for Protocol Handlers and Riverpod state management. | +| **Phase 1: Dio Migration (Part 1\)** | Week 1 – Week 2 | \- Create a centralized Dio client with basic interceptors. \- Replace simple HTTP calls (GET, POST) with Dio equivalents. \- Implement tests to confirm basic REST call functionality. | +| **Phase 2: Dio Migration (Part 2\)** | Week 3 – Week 4 | \- Handle complex HTTP flows (multipart uploads, chunked requests). \- Add global request/response interceptors for auth and error logging. \- Run regression tests. \- Document changes for future contributors. | +| **Phase 3: Core Architecture Setup** | Week 5 | \- Establish Protocol Handler interface for different protocols. \- Define Riverpod providers for state management. \- Start drafting UI changes for new protocols (WebSocket, SSE, MQTT, gRPC). | +| **Phase 4: WebSocket Implementation** | Week 6 | \- Create WebSocket handler using dart:io WebSocket. \- Develop UI panel for WebSocket (URL input, connect/disconnect, message log). \- Write unit tests with mock/echo servers. | +| **Phase 5: SSE \+ MQTT Integration** | Week 7 – Week 8 | \- Implement SSE handler using Dio for streaming GET. \- Integrate mqtt\_client library for MQTT. \- Develop UI for MQTT topic management. \- Add unit tests and manual tests against a public broker. \- Code generation templates. | +| **Midterm Review** | End of Week 8 | \- Demonstrate Dio-based REST calls and working WebSocket, SSE, MQTT integration. \- Address any UI/UX feedback from mentors. | +| **Phase 6: gRPC Support (Base)** | Week 9 – Week 10 | \- Implement gRPC handler (unary calls) with ClientChannel. \- Integrate Riverpod for gRPC status and error handling. \- Write code generation for gRPC in one language (e.g., Python or Go). | +| **Phase 7: gRPC Advanced Features** | Week 11 | \- Add support for server-streaming and bidirectional streaming calls. \- Experiment with reflection-based service discovery. \- Expand gRPC code generation to multiple languages. | +| **Phase 8: Polishing & Final Testing** | Week 12 | \- Fix remaining bugs and edge cases. \- Conduct cross-platform tests (Windows, Linux, macOS, Android). \- Optimize performance (e.g., message handling, memory management). \- Finalize documentation and prepare demos/screenshots. | + diff --git a/doc/proposals/2025/gsoc/application_Abhinav_Sharma_API_Testing_Suite.md b/doc/proposals/2025/gsoc/application_Abhinav_Sharma_API_Testing_Suite.md index 709df1b4..3217e5b9 100644 --- a/doc/proposals/2025/gsoc/application_Abhinav_Sharma_API_Testing_Suite.md +++ b/doc/proposals/2025/gsoc/application_Abhinav_Sharma_API_Testing_Suite.md @@ -30,6 +30,7 @@ **Have you worked on or contributed to a FOSS project before?** Yes, I have contributed to various FOSS projects, including APIDash. Here are some relevant PRs and repository links: +- [Implemented Fake Data Providers for API Dash to streamline testing](https://github.com/foss42/apidash/pull/777) - [Feature that allows users to configure and use a proxy for their HTTP requests within the API Dash](https://github.com/foss42/apidash/pull/544) - [Support for running multiple API requests in parallel](https://github.com/foss42/apidash/pull/734) - [Support for fetching environment variables directly from the OS in API Dash](https://github.com/foss42/apidash/pull/662) @@ -39,15 +40,24 @@ Yes, I have contributed to various FOSS projects, including APIDash. Here are so - [Dependency upgradation in Talawa](https://github.com/PalisadoesFoundation/talawa/pull/2353) **What is your one project/achievement that you are most proud of? Why?** -The project I'm most proud of is MapIt, a location-based note-taking app I built using Flutter. It allows users to create notes, tag locations using Google Maps, and set reminders with notifications. What makes this project special is that it combines multiple advanced features like Google Sign-In, Geofencing, Background Notification Service, and Battery Optimization to ensure a smooth user experience. -One of the most challenging yet rewarding aspects was implementing background services efficiently, ensuring notifications and location tracking worked even when the app was closed, without draining the battery. I also optimized the Isolates to handle background tasks asynchronously, improving app performance. -This project pushed me to learn state management, background execution, and efficient API handling. Seeing it come together and solving real-world problems with it made me really proud. +As part of the core engineering team, I collaborated with product managers and designers to prototype Neo, an AI-powered productivity assistant. My key contribution was architecting the natural language processing (NLP) pipeline that powers its automation features. Working closely with backend engineers, I developed models to extract user intent, deadlines, and emotional cues from voice/text inputs, which enabled features like smart scheduling and action plan generation. To ensure scalability, I integrated hybrid logic (ML models + rule-based systems). + +The cross-functional effort paid off – our team’s prototype was showcased on Shark Tank India, securing funding from 3 investors. This experience taught me how to balance technical innovation with product thinking in fast-paced, collaborative environments. + +[App URL](https://play.google.com/store/apps/details?id=xyz.neosapien.neo) + +Earlier, I engineered MapIt (a Flutter-based location-note app) to solve spatial memory challenges. It integrated geofencing, Google Maps, and battery-efficient background services. The complex dance of optimizing Dart Isolates for asynchronous geolocation tracking – ensuring notifications fired reliably even with the app closed – taught me valuable lessons in state management and performance tuning. + +Both projects pushed me to solve critical technical hurdles: Neo demanded scalable architecture for real-time voice/data processing, while MapIt required deep platform-level understanding of Android/iOS background execution limits. Together, they reflect my focus on building systems that augment human capabilities through thoughtful technical design. + +[Project URL](https://github.com/etackel/mapit_mobile) + **What kind of problems or challenges motivate you the most to solve them?** I love working with Flutter and creating automation solutions for real-world problems that help users worldwide. The ability to build applications that streamline workflows, reduce manual effort, and enhance user experience excites me the most. I strive to solve practical problems that users face daily by developing scalable and user-friendly applications. My passion lies in integrating different technologies, optimizing performance, and refining processes to improve developer productivity. Whether it's automating API testing, optimizing background processes, or designing intuitive UI/UX solutions, I always aim to create impactful applications that make a difference. **Will you be working on GSoC full-time?** -Yes, I will be dedicating my full time to GSoC. +Yes, I will be dedicating my full time to GSoC till end of July, then after that I would be able to give 15-20 hours per week due to my coursework. **Do you mind regularly syncing up with the project mentors?** Not at all, I am comfortable with regular sync-ups. @@ -84,18 +94,26 @@ By integrating these features, I will enhance APIDash to provide an end-to-end A ## Detailed Description -### Key Features: +### Key Features by Priority: -- **API Validation Testing**: I intend to implement schema validation and assertion checks. -- **Integration Testing**: I need to ensure seamless interactions between APIs. -- **Security Testing**: I plan to develop features to identify vulnerabilities & secure endpoints, along with detection of security breaches like script injection. -- **Performance Testing**: I aim to create tools to measure API performance under load. -- **Scalability Testing**: I will implement features to ensure APIs scale efficiently. +#### P0 (Must-Have Core Features): - **Collection Runner**: I plan to develop functionality to automate batch API executions, along with variable data payload sending ability. +- **API Validation Testing**: I intend to implement schema validation and assertion checks. - **Workflow Builder**: I aim to create a drag-and-drop API request chaining interface. - **Monitoring System**: I will implement a system to track API responses and errors. + +#### P1 (High-Value Additions): +- **Performance Testing**: I aim to create tools to measure API performance under load. +- **Integration Testing**: I need to ensure seamless interactions between APIs. +- **Security Testing**: I plan to develop features to identify vulnerabilities & secure endpoints, along with detection of security breaches like script injection. +- **Scalability Testing**: I will implement features to ensure APIs scale efficiently. +- **Automated fake data generation**: I plan to implement functionality to generate diverse and random data to send with the API requests. + +#### P2 (Extended Capabilities): - **Sync with authentication providers**: I plan to integrate authentication services for seamless API test management. - **Implement a global search bar**: I aim to add functionality for quick navigation and feature discovery. +- **Export API test results**: I plan to implement functionality to export API test results in various formats, such as CSV, JSON, or PDF. +- **Performance Insights** - Create load testing tools with flexible metrics integration (Prometheus optional) for monitoring and alerting. **AI-Enhanced Features (if time permits):** @@ -110,6 +128,7 @@ By integrating these features, I will enhance APIDash to provide an end-to-end A - **Backend**: Firebase or Node.js/Golang (if required for logging and monitoring) - **Testing Framework**: Postman alternatives, automated test scripts - **AI-Model**: Gemini or similar (If Required) +- **Monitoring & Alerting Toolkit**: Prometheus ![API Testing Suite](images/api-testing-suite-1.png) @@ -213,6 +232,39 @@ In this approach, my goal is to represent each API request as a node in the DAG, - I need to display successful requests in green (indicating an HTTP 200 status), while failed requests will be shown in red, instantly signaling an error state. - My implementation includes a central state repository using Riverpod providers that stores API request outputs (headers, bodies, tokens) in memory during workflow execution. This state repository will follow APIDash's existing pattern of immutable state objects while providing a mechanism for downstream nodes to access upstream outputs. + +Here's an implementation of the topological sort algorithm that will be used for executing API workflows in the correct order: + +```dart +List topologicalSort(List nodes) { + final sortedNodes = []; + final inDegree = Map.fromIterable(nodes, value: (_) => 0); + + // Calculate in-degree for each node + for (final node in nodes) { + for (final dep in node.dependencies) { + inDegree[dep] = (inDegree[dep] ?? 0) + 1; + } + } + + // Initialize queue with nodes having no dependencies + final queue = nodes.where((n) => inDegree[n] == 0).toList(); + + // Process nodes in topological order + while (queue.isNotEmpty) { + final node = queue.removeLast(); + sortedNodes.add(node); + + // Update in-degree of dependencies + for (final dep in node.dependencies) { + inDegree[dep] = (inDegree[dep] ?? 0) - 1; + if (inDegree[dep] == 0) queue.add(dep); + } + } + + return sortedNodes; +} +``` - I'm planning to implement execution controls with start, pause, and exit flags, allowing the workflow to be initiated, temporarily halted, or completely terminated without losing progress. **Conditional Execution Support** @@ -235,6 +287,10 @@ It's critical that I validate complex workflows involving multiple requests, dep - My testing strategy includes monitoring memory consumption and performance, ensuring large or long-running workflows do not degrade the user experience. - I aim to include an export feature that saves the workflow's execution results in JSON format, allowing teams to share and review outcomes easily. +Current Prototype: + +![](images/api-testing-suite-5.png) + ### Phase 5: API Testing Suite (Weeks 9-10) **Objective:** In this phase, I need to develop a completely new API Testing Suite to validate API responses with schema validation and assertions. This functionality will be built from the ground up as it's not currently implemented in APIDash. @@ -253,6 +309,30 @@ In this phase, I need to develop a completely new API Testing Suite to validate - As part of this work, I'll create simulations for high-traffic scenarios. - My testing framework will measure API response latency and throughput. +Below is a sample implementation of the load testing scheduler that will generate request timestamps based on the test configuration: + +```dart +List generateRequestTimestamps(LoadTestConfig config) { + final timings = []; + + // Handle concurrent users simulation + if (config.type == LoadTestType.concurrentUsers) { + // For concurrent users, all requests start at the same time + timings.addAll(List.filled(config.value, 0)); + } + + // Handle requests-per-second simulation + if (config.type == LoadTestType.rps) { + // Calculate interval between requests in milliseconds + final interval = (1000 / config.value).round(); + // Generate evenly spaced timestamps + timings.addAll(List.generate(config.value, (i) => i * interval)); + } + + return timings; +} +``` + **Security Testing Integration:** - I intend to build systems to detect vulnerabilities like CORS misconfigurations, exposed secrets. - My goal is to provide warnings for common API security flaws. @@ -325,11 +405,13 @@ To ensure project completion within the GSoC timeline, I've prioritized features - Collection Runner with basic sequential and parallel execution - Simple Workflow Builder with linear API chaining - Basic API validation testing +- Security testing features +- Automated fake data generation for API testing to reduce manual work **Extended Goals (If Time Permits):** - Advanced workflow conditionals and branching -- Security testing features - Performance testing capabilities +- Flexible metrics integration: Giving users options to either set up their own Prometheus server to scrape metrics from APIDash's exposed endpoint or use APIDash's built-in visualization of these metrics without requiring a full Prometheus server setup **Stretch Goals (Post-GSoC):** - AI-enhanced features diff --git a/doc/proposals/2025/gsoc/application_Prashant Nayak_Dashbot.md b/doc/proposals/2025/gsoc/application_Prashant Nayak_Dashbot.md new file mode 100644 index 00000000..93d528b8 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_Prashant Nayak_Dashbot.md @@ -0,0 +1,155 @@ +# GSoC Proposal: Dashbot For APIDash + ## About +- FULL NAME:PRASHANT NAYAK + - EMAIL : hydraprashant8@gmail.com +- PHONE:+917394060751 +- Discord Handle : prashant_1n_80322 +- Github Profile : https://github.com/Prashant1git +- Time zone : Asia /Jhansi ( IST) +- Resume Link : + https://drive.google.com/file/d/1Dt08bxtUQdnUL9UxTiOSt74zE1iwaAxg/view?usp=drivesdk + ## University Info + - University Name: Bundelkhad university + -Program: information and technology + -Year: 2nd Year (2025 Batch) + -Expected Graduation Date: 2027 + -Motivation & Past Experience +## 1. FOSS Contributions + I haven't contributed to FOSS projects yet, but I recently downloaded the APIDash codebase to + mylocal machine and started exploring it to understand its structure and functionality. +## 2. Proud Achievement + One of myproudest achievements was winning a university-level hackathon where I built a fully + functional Ai supported mobile application within just 24 hours. The event challenged + participants to solve real-world problems under intense time pressure, and I took it as an + opportunity to push my limits. Using Python, Flutter and Dart ,I developed a complete app—from + UI design to backend integration—that impressed the judges with its functionality, performance, +GSoCProposal: DashbotForAPIDash + and user experience. This experience not only boosted my confidence as a developer but also + reinforced my ability to work efficiently under pressure, think creatively, and deliver high-quality + results within tight deadlines. +## 3. Challenges that Motivate Me + Challenges that push me to step out of my comfort zone and learn something new are what + truly motivate me. Whether it's solving a complex coding bug, building a feature I've never tried + before, or working under tight deadlines—I see these situations as opportunities to grow. I enjoy + the process of breaking down problems, finding solutions, and seeing the impact of my work. + The feeling of overcoming a tough challenge and turning it into a success keeps me driven and + passionate about what I do as a developer. +## 4. GSoC Commitment + I will be working part-time on GSoC, as I am a 2nd-year student and need to balance my studies + alongside the project. +## 5. Syncing with Mentors + Yes, I am open to regular sync-ups with project mentors to ensure steady progress. +## 6. Interest in APIDash + APIDash stands out because of its lightweight, Flutter-based architecture, making it a + highly efficient alternative to tools like Postman. I am particularly excited about the + potential of expanding its modular design, enhancing API discovery, and integrating AI +based automation for better API management. +## 7. Project Improvements + While APIDash provides a great developer experience, some areas for improvement include: + Improving UI responsiveness on lower-end devices. + Expanding API import/export options for better interoperability. + Enhancing API security validation and error handling mechanisms. +##GSoCProposal: DashbotForAPIDash + Project Proposal Information + Proposal Title: Dashbot for APIDash +## Conceptual ; + DashBot is an intelligent assistant built for API Dash that helps developers save time and boost + productivity by handling common API tasks through natural language. From explaining + responses and debugging errors to generating documentation, tests, visualizations, and + frontend integration code (like React or Flutter), DashBot is designed to be both powerful and + flexible. It features a modular architecture and includes benchmarking tools to help users + choose the best-performing LLM backend for their needs. The project brings together AI, Python, + Dart, and Flutter to create a seamless, developer-friendly experience +# Weekly Timeline ; + + + +### 4.Weekly Timeline + + +| Week | Goals/Activities | Deliverables | +|------|-------------------------------------------------------------|-----------------------------------------------------------------| +| 1 | Planning & Setup.| Set up project structure & repo integration Create evaluation metrics for LLM benchmarking. | +| 2 | Natural Language Input Parsing. | Design prompt engineering systemCreate evaluation dataset for parsing accuracy. | +| 3 |Explain & Identify Discrepancie. | Implement module to explain API responses Add detection for discrepancies between response & expected schemaBenchmark explanation accuracy across LLMs. | +| 4 | Debug Based on Status/Error. |Build module to debug based on response codes & messages Integrate context (headers, payload, previous requests)Evaluate LLMs on debugging accuracy with predefined errorsGSoCProposal: DashbotForAPIDash. | +| 5 | Generate API Documentation. | Design prompt & output template for docs Support OpenAPI + natural descriptions Compare LLMoutput with real-world. | +| 6 | Generate Tests from API . | Build functionality to create tests (e.g., unit/integration tests)Target frameworks: Postman, pytest, etc.Validate test coverage & LLM consistency. | +| 7 |Visualizations of API Responses . | Implement module to convert JSON to charts (Bar, Line, Pie)Use plotting libraries like Plotly, Chart.jsd options for user customization. | +| 8 |Generate Frontend Integration Code . | Generate API integration snippets (React, Flutter Include authentication, headers, error handlingEvaluate code quality and syntactic correctness. | +| 9 |Modular Agent & Plugin System. |Design modular architecture for DashBot (plug-and-play Each module works independently with shared context/state Add agent loop with memory/context switchingLLMEvaluation FrameworkBuild evaluation UI/CLI to compare model outputs . | +| 10 |LLMEvaluation Framework. | Build evaluation UI/CLI to compare model outputs Define metrics: accuracy, coherence, latency, token usageDocument how to test with different backends. | +| 11 | Testing & Documentation. | Unit + integration testing across modules Create usage guide for developers Document each module’s LLM prompt structure. | +| 12 |Polish, Deploy & Community Feedback . | Polish UI/UX Create demo videos & example use cases Gather feedback from community & iterate TechnicalFlowchart. | +; + + +#FlowChart + + - USERINTERFACE + Flutter (Desktop)| +### +- + NATURALLANGUAGEINPUT│ + (Flutter ➜ Python API) + + + + COREPYTHONBACKEND(AGENTSYSTEM) │ +-Intent Parser (LangChain/OpenAI) │ + -Context Manager & Memory + -TaskRouter (Decides module) + + + + + -EXPLAIN -DEBUGMODULE -DOCGEN + │RESPONSE -Status/Error -OpenAPI/NL + + + - + TESTGEN PLOTS/VIS FRONTEND + (pytest) (Plotly) SNIPPETS + + + - LLMINTEGRATIONLAYER + - + -OpenAI / Claude / Local (via LangChain) + -Prompts + Output Parsers + Benchmarks + + -EVALUATIONFRAMEWORK + - Accuracy, Speed, Cost + - Compare LLMBackends + - CLI/GUI Benchmarks + + + + + -TESTING LAYER + + - Unit + Integration Tests │ + - Test LLMdeterminism + - CI/CD Integration + + +## Key Technologies by Layer + Frontend (Flutter/Dart): UI to input natural language and display results. + Backend (Python): Handles AI agent logic, modular routing, and LLM + interaction. + Agent System: Parses intent, routes to correct module (e.g., debugging, doc + gen). + LLMs: Handles understanding, generation, explanation tasks. + Evaluation Framework: Benchmarks LLM outputs across different + providers. +GSoCProposal: DashbotForAPIDash + Testing: Ensures correctness of outputs, stability of agents/modules. +## Conclusion + DashBot makes API Dash smarter by using AI to help developers with tasks like + debugging, writing docs, and generating code using natural language. It's built with + Python and Flutter, and designed to be flexible and easy to improve. It also helps + compare different AI models, making it a helpful open-source tool for developers. + Thisprojectaligns + wellwithmyskillsandinterests,andIa + meagertocontributetothe + APIDashecosyste + mthroughthisproject diff --git a/doc/proposals/2025/gsoc/application_RabbiyaRiaz_API_Explorer.md b/doc/proposals/2025/gsoc/application_RabbiyaRiaz_API_Explorer.md new file mode 100644 index 00000000..e998d24b --- /dev/null +++ b/doc/proposals/2025/gsoc/application_RabbiyaRiaz_API_Explorer.md @@ -0,0 +1,242 @@ + +### GSoC Proposal: API Explorer for API Dash + +#### About + +**Full Name:** + Rabbiya Riaz + +**Contact Info:** + - **Email:** rabbiyariaz2@gmail.com + +**Discord Handle:** + rabbiya0453 + +**GitHub Profile Link:** + [https://github.com/rabbiyariaz](https://github.com/rabbiyariaz) + +**LinkedIn:** + [https://www.linkedin.com/in/rabbiya-riaz-4b700224a/](https://www.linkedin.com/in/rabbiya-riaz-4b700224a/) + +**Time Zone:** + GMT+5 (Asia/Karachi) + +**Link to Resume:** + [https://drive.google.com/file/d/1c8MOBYc3hm6UuFkiyQTkK5A-CNzMvLqX/view](https://drive.google.com/file/d/1c8MOBYc3hm6UuFkiyQTkK5A-CNzMvLqX/view) + +#### University Info + +**University Name:** + National University of Sciences and Technology (NUST) + +**Program Enrolled:** + BS Computer Science + +**Year:** + 3rd Year + +**Expected Graduation Date:** + June 2026 + +#### Motivation & Past Experience + +**Have you worked on or contributed to a FOSS project before? Can you attach repo links or relevant PRs?** + No, I have not contributed to a FOSS project before. However, I am eager to start contributing to the API Dash open-source project and build my experience in the process. + +**What is your one project/achievement that you are most proud of? Why?** + The achievement I’m most proud of is my dedicated progress through Dr. Angela Yu’s “100 Days of Code: The Complete Python Pro Bootcamp” course on Udemy, where I built a variety of real-world projects that significantly honed my technical and problem-solving skills. I worked through the majority of the curriculum, developing tools like: + - A Spotify playlist automation system (using Selenium and Spotipy to track Billboard’s top songs) + - A flight deal finder (integrating Amadeus and Sheety APIs) + - A weather reporting application (via OpenWeather API) + - A price tracker that sends email alerts when prices drop + + This accomplishment is meaningful because it demonstrates consistency and perseverance, deepened my Python expertise, and taught me critical API integration and automation workflows—turning abstract ideas into functional tools. + +**What kind of problems or challenges motivate you the most to solve them?** + I am most motivated by challenges that require critical thinking and the ability to break down complex problems into manageable parts. I enjoy focusing on one problem at a time to devise creative and effective solutions. + +**Will you be working on GSoC full-time? In case not, what will you be studying or working on while working on the project?** + According to the GSoC 2025 timeline, the coding period begins on June 2. My semester is expected to end around that time, which will allow me to commit full-time to GSoC during my summer vacation. + +**Do you mind regularly syncing up with the project mentors?** + Not at all. I believe that regular and clear communication is essential for the success of any project, and I am committed to syncing up with the project mentors on a regular basis. + +**What interests you the most about API Dash?** + I have hands-on experience working with APIs and appreciate the clarity of well-formatted API requests. API Dash stands out because it offers a clean, simple interface that makes it easy for users to understand and work with APIs. Additionally, my experience in web scraping has sparked my interest in automation, and I see API Dash as a great opportunity to further enhance my skills in API management and automation. + +**Can you mention some areas where the project can be improved?** + + **Advanced Navigation and Filtering:** Develop a sidebar filter with checkboxes for predefined categories (e.g., AI, Finance, Weather, Social Media) and a dynamic search bar that auto-suggests API names or keywords. This ensures users can pinpoint the API they need with minimal effort. + + **Streamlined GitHub Workflow:** Enhance the contribution process by integrating GitHub’s API to fetch real-time pull request statuses and comments. For example, a “Contributions” tab on the dashboard could show pending PRs, automated test results from GitHub Actions, and a summary of reviewer comments. + +#### Project Proposal Information + +##### Proposal Title + +**Automated API Explorer and Template Generator for Enhanced API Dash Integration** + +##### Abstract + +This project proposes to build an automated API Explorer integrated into API Dash to streamline the discovery, testing, and integration of public APIs. The solution will provide a centralized library where users can browse and search a curated set of popular public APIs initially manually added (5–10 APIs), including popular AI APIs from sources like *awesome-generative-ai-apis*. These APIs, organized into predefined categories (based on a subset of categories from *awesome-open-source-flutter-apps*), will come with pre-configured request templates that include authentication placeholders, sample payloads, and expected responses. + +In parallel, a backend automation pipeline will be developed to periodically parse API documentation (OpenAPI, HTML, and Markdown formats), auto-tag them using rule-based techniques, enrich the data with metadata, and generate standardized templates. Community feedback via ratings, reviews, and GitHub contributions will ensure that the library remains accurate and up-to-date. This system is designed to reduce manual API configuration, improve onboarding time, and boost testing efficiency. + +##### Detailed Description + +###### Problem Statement + +Developers often face significant delays and errors when manually setting up API tests. Public APIs are documented in a variety of formats, which forces developers to repeatedly interpret and configure each endpoint, resulting in duplicated efforts, increased cognitive load, and inconsistent testing setups. There is no unified system that automatically extracts, categorizes, and standardizes API configurations for one-click import into testing environments. + +###### Proposed Solution + +The proposed solution consists of three integrated components: + +--- + +###### A. Front-End API Explorer + +**Objective:** +Build a responsive, user-friendly dashboard within API Dash that allows users to easily discover, browse, and import public API endpoints into their testing workspaces. + +**Key Features and Design Considerations:** + +**Manual Curation (Initial Phase):** + Start by manually adding 5–10 popular public APIs, including high-demand AI APIs (from *awesome-generative-ai-apis*). + **Example APIs:** OpenWeatherMap for weather data, Twitter API for social media interactions, and a few AI-related endpoints. + +**Data Structure & API Template Specification:** + **API data** will be stored in a standardized JSON format. + Each API template will include: + **Basic Fields:** + - API Name (e.g., “Twitter API – Post a Tweet”) + - Category (Predefined: e.g., Social Media, AI, Finance, Weather) + - Endpoint URL & HTTP Method (e.g., POST `https://api.twitter.com/2/tweets`) + **Authentication:** + Type (e.g., Bearer Token) with a placeholder. + **Payload & Response Examples:** + Sample payload and expected response formats. + **Metadata:** + Descriptions, version info, usage tips, and any constraints. + + **UI Design:** + **Dashboard Layout:** + Card-based grid display with API cards. + **Search & Filter:** + Ability to filter APIs by predefined categories (subset from *awesome-open-source-flutter-apps*), HTTP method, and other attributes. + **Detailed View:** + Clicking on a card opens a detailed page with all API template information. + **Import Functionality:** + A one-click “Import” button that sends the template (via a POST request) to API Dash’s backend endpoint (e.g., `/workspace/import`), injecting the API configuration into the user's workspace. + +--- + +###### B. Backend Automation Pipeline + +**Objective:** +Develop a backend service to automate API data extraction, enrichment, categorization, and template generation. + +**Modules & Implementation:** + + **Parsing Module:** + **OpenAPI Parsing:** + Use libraries like `swagger-parser` or `redocly` to extract API details from OpenAPI documents (.json or .yaml). + **HTML/Markdown Parsing:** + Utilize BeautifulSoup (for HTML) and Markdown parsers. + Leverage NLP techniques using Hugging Face Transformers (e.g., BERT) to detect key sections (e.g., "Endpoints," "Authentication") in unstructured documentation. + + **Auto-Tagging & Data Enrichment:** + **Rule-Based Engine:** + Apply a rules engine (e.g., Python's `rule-engine`) to infer defaults (e.g., `limit=10` for pagination) and enrich data with usage tips. + **Predefined Categories:** + APIs will be auto-tagged to a subset of predefined categories (drawn from *awesome-open-source-flutter-apps*), such as AI, Finance, Weather, and Social Media. + + **Template Generator:** + Generate final JSON templates that encapsulate all the parsed and enriched data. + Ensure the output conforms to the standardized schema for easy import into API Dash. + + **Error Handling & Logging:** + Log parsing errors and enrichment failures using Elasticsearch. + Implement retry logic (via Celery) for recoverable errors, with a maximum of three attempts. + + **Pipeline Scheduling:** + The pipeline will run periodically (once a week) or on-demand when new APIs are added, ensuring the API library remains up-to-date. + + +###### C. Community Feedback and Version Control + +**Objective:** +Facilitate community curation of the API library through ratings, reviews, and contributions. + +**Implementation Details:** + + **User Feedback System:** + Allow users to submit ratings (1–5 stars) and written reviews for each API template. + Store feedback in PostgreSQL with an appropriate schema and enforce rate limiting (e.g., max 5 reviews per user per hour). + + **Contribution Workflow via GitHub:** + Host the API template library in a public GitHub repository. + Enable users to propose updates or add new templates via pull requests. + Utilize GitHub Actions for CI/CD to validate JSON schema compliance and run unit tests on new submissions. + Manual reviews by maintainers to ensure security and quality. + **Change Tracking:** + Maintain version history with changelogs for each API template. + +--- + +#### 4. Weekly Timeline (Aligned with GSoC) + +##### Community Bonding Period (May 8 – June 1) + + **Onboarding & Planning:** + - Familiarize with API Dash’s codebase and contribution guidelines. + - Research high-demand public APIs (e.g., GitHub, OpenWeather, Stripe, popular AI APIs). + - Define and validate the JSON schema for API templates. + - Design initial wireframes for the API Explorer dashboard. + - Engage with mentors and the community to refine architectural decisions. + +##### Coding Phase Begins (June 2) + +###### Weeks 1–4 (June 2 – July 1) +**Milestone:** MVP Frontend and Initial Dataset Complete + +- Develop the API Explorer dashboard UI using React and Material-UI. +- Implement card-based display, search, and filtering features. +- Manually add 5–10 curated APIs across predefined categories (e.g., AI, Finance, Weather, Social Media). +- Build the "Import" functionality to allow one-click insertion into the workspace. +- Finalize and test the initial JSON schema for API templates. + +###### Weeks 5–7 (July 2 – July 18) +**Milestone:** Backend Pipeline Prototype + Midterm Evaluation + +- Implement the OpenAPI parser using `swagger-parser`. +- Develop the HTML/Markdown scraper using BeautifulSoup and NLP models (e.g., BERT). +- Create the rule-based engine for auto-tagging and data enrichment. +- Set up PostgreSQL tables for storing enriched API data. +- Integrate the backend pipeline with the front-end to display generated templates. +- Prepare a demo for the midterm evaluation, showcasing the complete flow from parsing to importing. + +###### Weeks 8–10 (July 19 – August 25) +**Milestone:** Automation Expansion and Community Features + +- Finalize the template generator to produce standardized JSON API templates. +- Implement the “Import” API endpoint to push templates into the testing environment. +- Integrate Redis caching for frequently accessed API templates. +- Develop the user feedback (ratings and reviews) system. +- Enable GitHub-based contributions with CI/CD via GitHub Actions. +- Optimize and polish both the backend and frontend components. +- Conduct usability testing with real users to gather feedback. + +##### Final Week (August 26 – September 1) + +- Conduct a full QA cycle including integration tests, unit tests, and UX validation. +- Finalize comprehensive documentation covering the template schema, contribution processes, and developer setup. +- Submit final code deliverables, evaluation report, and prepare a presentation for final evaluation. + +##### Post-Submission (Optional Extensions) + +- Monitor community PRs and integrate additional API templates. +- Extend parser support to additional formats (e.g., GraphQL). +- Explore machine learning-based classification for undocumented APIs. +- Further optimize performance and scalability based on user feedback. + diff --git a/doc/proposals/2025/gsoc/application_SalaPavan_api-testing.md b/doc/proposals/2025/gsoc/application_SalaPavan_api-testing.md new file mode 100644 index 00000000..32041763 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_SalaPavan_api-testing.md @@ -0,0 +1,167 @@ +### About + +1. Sala Pavan Sai Teja Kishore +2. Email : pavankishore2203@gmail.com +3. Phone : +91 6303141184 +4. Discord handle : spavansaitejakishore +5. GitHub profile link : https://github.com/SPavanKishore/ +6. LinkedIn : https://www.linkedin.com/in/s-pavan-kishore-b19383218 +7. Time zone : IST(+5.30) +8. Resume : https://drive.google.com/file/d/1HQM_FNaDH_2td2YWuJtbo5JnINmG4ngw/view?usp=sharing + +### University Info + +1. Indian Institute of Technology (IIT) Tirupati +2. Computer Science and Engineering +3. 2020-2024 + +### Motivation & Past Experience + +Short answers to the following questions (Add relevant links wherever you can): +1. Have you worked on or contributed to a FOSS project before? + No, I haven't worked on FOSS project before, I am waiting to contribute. +2. What is your one project/achievement that you are most proud of? Why? + One of my energetic projects is BlueVa, which is building logic using code-blocks provided, designed canvas to allow user make logic, + its like Java game for beginners to explore, so after completing canvas, this tool will generate code for logic and will show errors if any. + This project is like teaching a language, so this project made me teach and understand what and how I did things. +3. What kind of problems or challenges motivate you the most to solve them? + Puzzles are most motivating challenges, cause they dont have straight solution, they give space to think and analyse and every analysis will contribute to solutionn somehow. + So such puzzles in development are optimization, scalability, real-time analysis. So these kind of challenges will try to solve. +4. Will you be working on GSoC full-time? In case not, what will you be studying or working on while working on the project? + I will be working completely on GSoC and open-source contribution. +5. Do you mind regularly syncing up with the project mentors? + If project needs regular-syncups then it is good to have them. +6. What interests you the most about API Dash? + I worked on APIs recently, so now this API Dash will make to go in more deeper thoughts about api and api-testing. +7. Can you mention some areas where the project can be improved? + AI-driven api-testing and making suggestions for possible improvements for endpoints. + +### Project Proposal Information + +1. Proposal Title : AI-Powered API Testing and Tool Integration +2. Abstract: + Integrating APIs with AI agent frameworks like crewAI, smolagent, pydantic-ai, or langgraph + requires manual conversion of API endpoints into tool definitions-another time-intensive process. + This project aims to automate and enhance these workflows using Large Language Models (LLMs), making + API testing and integration smarter, faster, and developer-friendly + +3. Detailed Description +To build an AI agent that: + -Automates API testing using prompts. + -Converts APIs (OpenAPI specs or raw documentation) into structured tool definitions for testing + -Benchmarks and evaluates LLMs for optimal performance in test generation and tool creation + -Integrates with agent frameworks like crewAI, smolagent, pydantic-ai, and langgraph as mentioned + +4. Weekly Timeline: + +Week 1-2: Research & Planning +- Finalize target frameworks and API formats +- Research best-fit LLMs +- Define API testing criteria and tool definition schemas +- Tasks : + - Define problem scope (API types, test goals, output formats) + - Choose baseline LLMs (e.g., GPT-4, Claude, Mixtral, Mistral-Instruct, etc.) + - Study integration specs of crewAI, smolagent, pydantic-ai, langgraph + - Define evaluation metrics (accuracy, coverage, latency, cost) + - Set up project repo, issue tracker, CI/CD for deployments + - Prepare API collection (Swagger/OpenAPI/REST/GraphQL) +- Deliverables: + - Project blueprint & API collection + - Defined output schema for tool definitions & test cases + - Initial prompt templates + +Week 3-4: API Parsing & Tool Generation Module +- Build parsers for OpenAPI and Swagger +- Generate tool definitions for popular agent frameworks +- Tasks: + - Create OpenAPI parser using Python (pydantic, openapi-spec-validator) + - Add feedback for parsing raw text descriptions + - Make prompt templates for converting API specs to: pydantic-ai function signatures,crewAI tools,Langgraph nodes + - Validate tool formats via auto-regression tests + - Build minimal CLI: python generate_tools.py --api_spec sample.json +- Deliverables: + - API parser module (OpenAPI, raw docs) + - Initial prompt-to-tool-definition pipeline + - Sample tool outputs across 3 agent frameworks + +Week 5-6: API Testing Engine +- Accept natural language test scenarios +- Generate test cases +- Execute tests and validate responses +- Tasks: + - Create NL2TestCase prompt templates (e.g., "Test login with invalid password") + - Use LLM to: + - Parse prompt into method + params + - Generate edge cases and parameter variations + - Implement the executor (requests/httpx) to call endpoints + - Implement LLM-based validator: + - Match response schema + - Check for expected fields/values + - Score for correctness and performance + - Add basic metrics: latency, response size, status codes +- Deliverables: + - test_runner.py with support for JSON/REST APIs + - LLM prompt templates for test generation + - Sample outputs and test logs + +Week 7-8: Agent Framework Integration +- Wrap test functions for agent compatibility +- Build CLI and optional Flutter web frontend +- Tasks: + - Wrap test modules and tool definitions for: + - crewAI agents with roles (tester, validator, reporter) + - smolagent function chains + - pydantic-ai function registry + - Create orchestrator: + - Accept test goals in natural language + - Select relevant APIs/tools + - Chain test generation → execution → validation + - Provide CLI: agent test_sample_api.yaml "" +- Deliverables: + - Agent orchestration modules + - CLI interface for testing flows + - Compatibility will be tested across 3 frameworks + +Week 9: Benchmarking & Evaluation +- Create a benchmark dataset +- Compare LLMs for performance and cost on identical tasks +- Tasks: + - Collect 10–20 APIs (public and varied: weather, books, finance, auth, etc.) + - Write 30–50 natural language test prompts and expected outcomes + - Create test matrix: + - API, prompt, model used, output, validation score + - Run tests on: GPT-4, Claude, Mixtral/Mistral-Instruct, Command R+ + - Log the results with latency, tokens (if API-based) +- Deliverables: + - benchmark.jsonl with labeled prompts, inputs,outputs + - Evaluation script + scoring logic + - LLM comparison table (charts if needed) + + +Week 10: Finalize +- Documentation and demo +- Tasks: + - Add Logging-retries in test ececutor + - try new prompt versions + - Failure recovery for bad input + - Write Dev and user documentation + - Prepare Integration guide for frameworks used + - Make demo APIs and walkthroughs(if nay) +- Deliverables: + - Final CLI + - Build lightweight web UI (Streamlit/Flet/Flutter Web) + - Packaged tools by Python-module or docker image + - Documentation and guide + + +This timeline has significant flexibility to add or modify tasks. + +#Tools +- Languages: Python, Dart (for optional Flutter frontend) +- Frameworks: crewAI, smolagent, pydantic-ai, langgraph (as mentioned) +- LLMs: GPT-4, Claude +- Libraries: LangChain, FastAPI, httpx +- Others : Docker, Git, Jupyter, pytest + + + diff --git a/doc/proposals/2025/gsoc/application_VisheshJain_SmartJSONEditor.md b/doc/proposals/2025/gsoc/application_VisheshJain_SmartJSONEditor.md new file mode 100644 index 00000000..37242445 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_VisheshJain_SmartJSONEditor.md @@ -0,0 +1,89 @@ +# Google Summer of Code 2025 - Application + +## 👤 About Me + +- **Name**: Vishesh Jain +- **Email**: [visheshj2005@gmail.com](mailto:visheshj2005@gmail.com) +- **Phone**: +91 9664049426 +- **Portfolio**: [visheshj2005.netlify.app](https://visheshj2005.netlify.app) +- **GitHub**: [github.com/visheshj2005](https://github.com/visheshj2005) +- **LinkedIn**: [linkedin.com/in/visheshj2005](https://www.linkedin.com/in/visheshj2005/) +- **Time Zone**: IST (UTC+05:30, Kolkata) + +--- + +## 🎓 University Information + +- **Institution**: Techno India NJR Institute of Technology +- **University**: Rajasthan Technical University +- **Program**: B.Tech in Computer Science and Engineering +- **Current Year**: 2nd Year +- **Expected Graduation**: July 31, 2027 + +--- + +## 💡 Motivation & Past Experience + +As a passionate developer, I enjoy working on projects that solve real-world problems. I discovered open source through community-driven projects and was immediately drawn to the collaborative and impactful nature of it. + +Participating in GSoC is a chance to work on meaningful contributions under mentorship while improving my coding, collaboration, and problem-solving skills. I am eager to contribute to API Dash, a project that aligns with my interests in backend development, APIs, and Flutter. + +--- + +## 📄 Project Proposal Information + +### **Proposal Title**: +**Enhancing JSON Body Editor in API Dash** + +### **Abstract**: +This project proposes improvements to the JSON body editor within API Dash. Key features include syntax highlighting, JSON validation, and beautification. These additions will significantly improve usability and reduce common errors when editing API requests. + +--- + +## 📘 Detailed Description + +### **Introduction** +API Dash is a cross-platform API client built using Flutter. While it supports composing HTTP and GraphQL requests, its JSON body editor lacks several features crucial for developer productivity. + +### **Problem Statement** +The current JSON body editor is basic. Developers often require real-time syntax checking, validation, and formatting while constructing JSON payloads. The absence of these features can lead to inefficiencies and avoidable errors. + +### **Objectives** + +- Implement syntax highlighting for better code readability. +- Add JSON validation to help users quickly identify formatting or structural issues. +- Provide a beautification tool to auto-format JSON for cleaner presentation. + +### **Methodology** + +1. **Research**: Analyze other popular API tools (like Postman or Insomnia) to gather insights into best practices. +2. **Syntax Highlighting**: Use existing Flutter packages like `highlight` or `flutter_highlight` to implement. +3. **JSON Validation**: Implement a real-time validator using Dart’s `jsonDecode()` wrapped in error handling. +4. **Beautification**: Use packages or custom logic to pretty-print JSON with indentation and proper formatting. +5. **Integration**: Seamlessly integrate all new features into the existing codebase with modular design. +6. **Testing**: Ensure all features are unit tested and manually tested across platforms (Windows, macOS, Linux). + +--- + +## 🗓 Weekly Timeline + +| Week | Task | +|------|------| +| 1–2 | Set up the development environment. Study the codebase. Define implementation plan. | +| 3–4 | Design and begin implementation of the syntax highlighting feature. | +| 5–6 | Complete syntax highlighting; write tests and conduct initial feedback testing. | +| 7–8 | Develop JSON validation logic with error feedback mechanism. | +| 9–10 | Integrate JSON beautification tool and test on different payloads. | +| 11–12 | Perform extensive cross-platform testing and resolve reported issues. | +| 13 | Final refinements, documentation, and submission of final work report. | + +--- + +## ✅ Expected Outcomes + +- A fully functional JSON body editor in API Dash with: + - Syntax highlighting + - Real-time validation + - One-click beautification +- Clean, documented, and tested code merged into the upstream repository. +- Improved developer experience and fewer errors during API request composition. diff --git a/doc/proposals/2025/gsoc/application_bhushan_AI_Agent_for_API_Testing_Tool_generation.md b/doc/proposals/2025/gsoc/application_bhushan_AI_Agent_for_API_Testing_Tool_generation.md new file mode 100644 index 00000000..07a3497b --- /dev/null +++ b/doc/proposals/2025/gsoc/application_bhushan_AI_Agent_for_API_Testing_Tool_generation.md @@ -0,0 +1,128 @@ +# GSoC’25 Proposal – Api Dash +## AI Agent for API Testing & Tool Generation + +![Project Image](./image.png) + +--- + +## Personal Details + +- **Name:** Bhushan Bharat +- **Course:** BTech CSE +- **Email:** [bhushanbharat6958@gmail.com](mailto:bhushanbharat6958@gmail.com) +- **GitHub:** [bbl-sh](https://github.com/bbl-sh), [john221wick](https://github.com/john221wick) +- **LinkedIn:** [Bhushan Bharat](https://www.linkedin.com/in/bhushan-bharat-51ba4825b/) +- **Phone:** 7909073248 +- **Country:** INDIA +- **Resume/CV:** [Resume Link](https://drive.google.com/file/d/1di1XTSOw8C9xMpKPW94LQwbRaHlXkzLj/view?usp=drive_link) +- **Portfolio:** [Portfolio](https://portfolio-bhushans-projects-ab4d9b37.vercel.app/) +- **Demo:** [Demo Link](https://youtu.be/il35dcY8U4k?si=Yo7A6U1owad6kfan) +--- + +## Short Answers + +### 1. Have you worked on or contributed to a FOSS project before? +**No**, this will be my first contribution to a FOSS project. + +### 2. What is your one project/achievement that you are most proud of? Why? +Building an LLM and training it with PyTorch distributed (both GPT and LLaMA 3.2), although it's not complete yet. Additionally, I’ve developed an automated CI/CD agent, local research system, and Leetcode-style judge using the Judge0 API for real-time code execution. + +### 3. What kind of problems or challenges motivate you the most to solve them? +I am most motivated by challenges involving: +- Automation +- AI-driven problem solving +- Integration of advanced AI technologies with real-world software engineering + +### 4. Will you be working on GSoC full-time? +**Yes**, I will work on GSoC full-time. + +### 5. Do you mind regularly syncing up with the project mentors? +**No**, I am eager to have regular communication and feedback from mentors. + +### 6. What interests you the most about API Dash? +I’m particularly drawn to API Dash's ability to: +- Streamline API testing and debugging +- Integrate AI seamlessly into development workflows + +### 7. Can you mention some areas where the project can be improved? +- Better multi-language support +- Enhanced UI/UX +- Deeper AI integration for automated insights and optimization + +--- + +## Project Proposal Information + +### Proposal Title +**AI Agent for API Testing & Tool Generation** + +--- +**Demo:** [Demo Link](https://youtu.be/il35dcY8U4k?si=Yo7A6U1owad6kfan) + +### Abstract +This project introduces an AI agent to automate API testing and generate tools using LangGraph. It connects GitHub hooks to a FastAPI-powered backend, enabling automatic test case generation for API endpoints and returning detailed reports to the developer on commit. + +--- + +### Detailed Description + +**Demo:** [Demo Link](https://youtu.be/il35dcY8U4k?si=Yo7A6U1owad6kfan) + +![Workflow Diagram](./images/apiDash.png) +The system utilizes: +- A **GitHub commit hook** (triggered by `"generateTest"` in the commit message) +- A **bash (curl) script** to send code to the backend +- A **FastAPI** backend managed with **LangGraph** to execute node-based API test generation workflows + +#### Key Components: +- **LangGraph nodes:** Each node performs distinct testing or analysis tasks +- **Scalability:** Easy to add new nodes for more advanced tests +- **Report generation:** Summarized results delivered back to user + +#### Future Enhancements: +- Comprehensive node definitions +- Support for advanced test cases +- Rich reporting dashboard +- Authentication and secure GitHub interactions + +#### Technologies Used: +- Bash scripting +- Python +- LangGraph +- FastAPI +- Docker/Kubernetes (for deployment) + +--- + +### Weekly Timeline + +| Phase | Dates | Tasks | +|-------------|-------------------|----------------------------------------------------| +| Bonding | May 2025 | Understand system, sync with mentors | +| Week 1–4 | June 1 – June 30 | Basic API testing and tool generation pipeline | +| Week 5–8 | July 1 – July 31 | Extend node functionality for diverse test cases | +| Week 9–12 | Aug 1 – Aug 31 | Add cursor support and refine LangGraph nodes | +| Week 13–16 | Sept 1 – Sept 30 | Improve report generation and feedback mechanisms | +| Week 17–20 | Nov 1 – Nov 30 | Add authentication and secure API interactions | +| Week 21–24 | Dec 1 – Dec 31 | Final polish, demo deployment, and user testing | + +--- + +### Major Milestones + +- ✅ Prototype pipeline with test case generation – **June 30, 2025** +- ✅ Expanded node functionality and test types – **September 30, 2025** +- ✅ Fully operational AI-driven API testing tool – **December 30, 2025** + +--- + +### Additional Information +My background in: +- AI/ML +- DevOps/MLOps +- Full-stack development +…makes me a strong fit to execute this project successfully. I see this as an opportunity to build something impactful and learn alongside an expert open-source community. + +**I’m excited to grow, contribute, and build something meaningful with ApiDash!** + +--- diff --git a/doc/proposals/2025/gsoc/application_devanshsingh_dashbot.md b/doc/proposals/2025/gsoc/application_devanshsingh_dashbot.md new file mode 100644 index 00000000..89e05b59 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_devanshsingh_dashbot.md @@ -0,0 +1,91 @@ +### About + +1. **Full Name**: Devansh Singh +2. **Contact info**: devanshsingh1974@gmail.com +3. **Discord handle**: = @devansh_raghuvanshi +4. **Home page**: (optional, leave blank if none) +5. **Blog**: (optional) +6. **GitHub profile link**: https://github.com/Devansh1974 +7. **Twitter, LinkedIn, other socials**: + - LinkedIn: www.linkedin.com/in/devanshsingh2006 +8. **Time zone**: IST (GMT+5:30) +9. **Resume link**: [https://drive.google.com/file/d/1DcoIIQQp8AmTLtu4Aq91aLroHPh8_G_H/view?usp=sharing] + +--- + +### University Info + +1. **University**: Alliance University +2. **Program**: B.Tech in Software Product Engineering +3. **Year**: First Year (2024–2028) +4. **Expected graduation**: June 2028 + +--- + +### Motivation & Past Experience + +1. **Have you worked on a FOSS project before?** +Yes! I have recently started contributing to API Dash itself, with PRs like my DashBot idea submission. I’m eager to explore more open-source contributions with community engagement. + + +2. **One project/achievement you are proud of?** +My ongoing work on a stock market web app with AI-based alerts. I’m building it with the MERN stack and integrating features like AI chatbots and trivia quizzes. This project helped me improve my full-stack dev skills. + +3. **What kind of problems motivate you?** +Creative technical challenges that involve clean UI + backend logic. I love when I can combine UX and AI tools to solve real problems. + +4. **Will you work on GSoC full-time?** +Yes! I’m committed to dedicating full-time during the GSoC coding period. + +5. **Are you okay with regular mentor sync-ups?** +Absolutely yes. I'm very active on Discord and GitHub. + +6. **What interests you most about API Dash?** +The simplicity and speed of the app! It’s refreshing how lightweight it is compared to Postman. DashBot, especially, excites me because of the AI + dev tooling blend. + +7. **Areas to improve in the project?** +- AI-assisted user onboarding +- Chat-based debugging suggestions +- Clearer error interpretation for APIs +- Saving test histories across sessions + +--- + +### Project Proposal Information + +1. **Proposal Title**: DashBot – AI Assistant for API Dash + +2. **Abstract**: +DashBot is an intelligent assistant that enhances the API Dash user experience by providing a chat-based interface to help users write, debug, and understand API requests. It leverages LLMs to help beginners and pros alike work with APIs faster and with fewer errors. The assistant will be integrated as a widget within the app UI. + +3. **Detailed Description**: +- Integrate DashBot into the existing Flutter app as a chat UI. +- Build context-aware API guidance using a local LLM (or OpenAI fallback). +- Features: + - Natural language to API translation + - Error explanations and suggestions + - Autofill headers/body + - History of queries +- Structure: + - Backend service (Python/Node.js) to connect with LLM + - Frontend UI in Flutter using existing components +- Timeline involves: + - UI prototyping + - Backend API scaffolding + - LLM response formatting + - Testing and feedback integration + +4. **Weekly Timeline**: +_(Rough plan based on GSoC coding phases)_ + +| Week(s) | Activity | +|--------|----------| +| Community Bonding | Finalize scope, design chat UI, mentor sync-ups | +| Week 1–2 | Set up chat interface in Flutter | +| Week 3–4 | Build backend bridge to LLM, test with mock data | +| Week 5–6 | Integrate real LLM calls + prompt tuning | +| Week 7–8 | Add features: headers, body autofill, error explain | +| Week 9–10 | Feedback loop, refine UX, polish UI | +| Week 11–12 | Final testing, documentation, mentor demos | + +--- \ No newline at end of file diff --git a/doc/proposals/2025/gsoc/application_himanshu_api_testing_suite_workflow_builder.md b/doc/proposals/2025/gsoc/application_himanshu_api_testing_suite_workflow_builder.md new file mode 100644 index 00000000..6ee044cf --- /dev/null +++ b/doc/proposals/2025/gsoc/application_himanshu_api_testing_suite_workflow_builder.md @@ -0,0 +1,164 @@ + +--- + +### GSoC 2025 Proposal: Visual Workflow Builder & API Testing Suite for APIDash + +--- + +### Personal Information + +- **Full Name:** Himanshu Rajput +- **Email:** himanshu011raj@gmail.com +- **Phone:** +91 6378432331 +- **GitHub:** [maiHydrogen](https://github.com/maiHydrogen) +- **LinkedIn:** [himanshu-rajput](https://www.linkedin.com/in/himanshu-rajput-02980429a) +- **Discord:** @maiHydrogen +- **Time Zone:** GMT+5:30 (India) + +### University Information + +- **Institution:** Indian Institute of Technology Guwahati +- **Program:** B.Tech in Civil Engineering +- **Year of Study:** 2nd Year (2023) +- **Expected Graduation:** June 2027 + +--- +### Motivation & Past Experience  + +1. Have you worked on or contributed to a FOSS project before? Can you attach repo links or relevant PRs? +- I kicked off my open-source journey with Hacktoberfest ’24, landing 4 merged PRs across 3 repos (2 Flutter, 1 Python Flask)—my first taste of community coding! See, +the relevant PRs as follows – +[Flask 1]( https://github.com/Namit2111/bible-verse-finder/pull/50) [Flutter 1]( https://github.com/lugnitdgp/Aerocart/pull/11) [Flutter 2]( https://github.com/SankethBK/diaryvault/pull/258) [Flask 2]( https://github.com/Namit2111/bible-verse-finder/pull/54)  + +- I discovered APIDash recently and have already made multiple contributions, which demonstrate both my willingness to learn and my technical initiative: + +[#589](https://github.com/foss42/apidash/pull/589): Added Android-specific troubleshooting documentation.  + +[#680]( https://github.com/foss42/apidash/pull/680): Attempted implementation of Basic Auth (closed with valuable feedback).  + +[#689](https://github.com/foss42/apidash/pull/689): Implemented API Key and Bearer Token authorization (closed with valuable feedback)  + +2. What is your one project/achievement that you are most proud of? Why? + +- The project that I can mention here is one named as [“USay”]( https://github.com/maiHydrogen/USay). a real-time chat app I built solo as a rookie. Starting from scratch, I sketched the UI, coded the frontend, and wired Firebase for auth and messaging—culminating in a 2 a.m. triumph over a stubborn Google Sign-In bug to ship it, all while learning Dart on the fly. Now, it’s ready to have its own chatbot, video/voice call and most importantly end to end encryption very soon.USay taught me resilience—let’s build a tool that empowers developers worldwide! + +3. What kind of problems or challenges motivate you the most to solve them? + +- I thrive on challenges that push me off my limits like being 2nd-year B.Tech Civil Engineering student at IIT Guwahati, where I’ve carved my own path into software through sheer curiosity and mastering Dart’s async for USay or tackling APIDash’s Riverpod. The steeper the curve, the more I dig in—sure, I stumble (like my first auth PR), but each miss sharpens my next shot. Solving real dev pain points with tools like this suite keeps me hooked. + +4. Will you be working on GSoC full-time? In case not, what will you be studying or working on while working on the project? +- I’m all in for GSoC—full-time, 35+ hours/week, May to August 2025, thanks to summer break. I’ll tinker with ML and Dart extras on the side, but APIDash gets my prime focus. + +6. Do you mind regularly syncing up with the project mentors? + +- Absolutely not, I will be available for and absolutely love to syncing up with the project mentors for regular updates and guidance related to the project. +7. What interests you the most about API Dash? + +- What excites me about APIDash is its innovative use of Flutter and Dart for end-to-end API management. The project’s emphasis on native tooling (Riverpod, Melos, etc.) and unique monorepo structure presents a unique opportunity to innovate and push the boundaries of what's possible with Dart. Riverpod’s elegance and the maintainers’ positive behaviour make it a learning playground. Crafting a Figma prototype for this suite felt like joining the party early—can’t wait to build it! + +8. Can you mention some areas where the project can be improved? + +- API Dash is on a promising way. I have seen the **Roadmap** as well as other interesting ideas in the pipeline for GSoC. +- I would like to add that API Dash should be more present in the open-source events like Hacktoberfest and all so that it can gain ample amount of contributors which is most important thing to get the project rolling. +- It could shine brighter with tighter CI/CD hooks (e.g., GitHub Actions for test automation)  + +--- + +## Project Title + +Visual Workflow Builder & API Testing Suite for APIDash + +### Abstract:   +This project aims to integrate a robust, visual API testing suite directly into APIDash. By enabling users to design, run, and monitor API test flows entirely through a drag-and-drop interface, enhanced version of drawing from my Figma prototypes—[Workflow Canvas](images/Dashflow.png),[Monitor Setup](images/Monitors.png), [Runner Interface](Runner.png) and [Collection](images/collections.png). The solution will provide native support for request chaining (with variable injection), modular test suites, parallel execution, and real-time monitoring. With a focus on performance and usability, the suite will leverage Flutter’s UI capabilities and Dart’s asynchronous programming to offer an intuitive, high-performance alternative to existing API testing tools. + +#### Vision and Objectives +My goal is to weave a seamless API testing experience into APIDash, tailored to real-world needs: +- **Testing Suite**: A robust system for validation (custom assertions), integration, security scans, performance benchmarks, and scalability checks—organizable into nested, reorderable suites (#96). +- **Workflow Builder**: A drag-and-drop canvas (more refined version of design provided for reference above) to chain requests with dynamic variables (#120). +- **Collection Runner**: A flexible engine for async or parallel test execution with adjustable timeouts (#100). +- **Monitoring Dashboard**: A sleek sidebar with live latency charts and exportable JSON logs (#96, #120). + +### Technical Approach + +**Architecture Overview:** +- **Frontend:** + - Built in Flutter, the UI will use custom widgets and gesture detectors to implement an intuitive drag-and-drop system. + - Construct the workflow builder by leveraging Flutter’s `Draggable` for my Figma design, integrate Riverpod for state + - The Workflow Builder will render a directed acyclic graph (DAG) where each node corresponds to an API request, and edges represent the flow of execution. +- **State Management:** + - Riverpod will be utilized to manage application state, ensuring that node data, variable contexts, and test statuses are efficiently updated and propagated. +- **Async Execution:** + - Dart's asynchronous programming features (e.g., `Future.wait`, isolates) will power the test runner, enabling parallel API calls and real-time feedback. +- **Assertion DSL:** + - A domain-specific language (DSL) for assertions will be developed to allow users to define custom validations using simple syntax (e.g., `status == 200 && body.contains("success")`). +- **Functional test suite with sample assertions :** + - Build the testing suite’s foundation—design assertion logic, add security checks, and write unit tests. + ```dart + class TestValidator { + final String field, expectedValue; + TestValidator(this.field, this.expectedValue); + bool validate(dynamic response) { + var data = response is String ? jsonDecode(response) : response; + return data[field] == expectedValue; // Extensible for status, headers + } + } + ``` +- **Data Persistence:** + - Local storage (using Hive or SharedPreferences) will support saving and loading of test workflows and results, with a lightweight JSON schema for interoperability. + +**Innovative Technical Elements:** +- **Dynamic Variable Injection:** + - Implement a templating engine that processes variables in API requests, enabling dynamic chaining of requests and responses. +- **Optimized Parallelism:** + - Utilize Dart's `Future.wait` for concurrent request execution, and explore isolates for heavy computational tasks (like processing large datasets or extensive test suites). +- **Custom Visualization:** + - Develop interactive graphs within the monitoring dashboard to display latency metrics and test outcomes in real time, using packages like `fl_chart`. +- **Extensibility:** + - Design the architecture with modularity in mind, allowing for future integration with CI/CD pipelines and scheduled test automation. + +### Timeline + +| Period | Goals | +|--------|-------| +| **May 8 – June 1**
(Community Bonding) | - Engage with mentors and the APIDash community
- Thoroughly review APIDash's architecture and codebase
- Finalize detailed design, technical stack, and project scope
- Prototype Flutter drag-and-drop UI patterns and assess Riverpod usage
- Research DSLs and Flutter DAGsa and Mock UI for assertion engine & monitor| +| **June 2 – June 8**
(Week 1) | -Build base of testing engine (node model, assertion evaluator)
-Scaffold assertion DSL parser and basic validations +
-Unit test core validator module | +| **June 9 – June 15**
(Week 2) | - Integrate variable support and request chaining
- variable injection + chaining logic to engine (e.g., highlighting placeholders)
-Enable JSON schema-based API response validation,CLI for running test plans| +| **June 16 – June 22**
(Week 3) | - Build the initial Test Runner to execute chained requests
- Support both sequential and parallel execution using Dart's async features
- Display raw output logs for debugging purposes Build simple Collection Runner (sequential + parallel)| +| **June 23 – June 29**
(Week 4) | - Perform internal testing of request execution logic
- Polish UI interactions and refine drag-and-drop experience
- Add timeout & stop-on-failure logic Save/load test plans from local storage
+| **June 30 – July 6**
(Week 5) | - UI components for assertion configuration
- Begin integrating basic validations (status, header, body)
-Start Workflow Builder UI Create node editor (drag/drop, reorder, editable requests)
-Connect UI to test engine | +| **July 7 – July 13**
(Week 6) | - Extend the UI to support Test Suite organization (grouping, nesting, reordering)
-Add visual chaining of requests (edges, sequence)
-Enable configuring assertions visually| +| **July 14 – July 18**
(Week 7) | -Midterm Evaluation (should include test engine + basic workflow UI + variable chaining) +| **July 19 – July 25**
(Week 8) | - Implement advanced controls: asynchronous execution, timeouts, and stop-on-failure options
-Integrate a real-time Monitoring Dashboard displaying pass/fail status and latency charts | +| **July 26 - August 2**
(Week 9) | - Implement export functionality for test suites and results as JSON
Implement UI for suite grouping, toggling, solo-run| +| **August 2 - August 8**
(Week 10) | -Sync all UI states with Riverpod
-Conduct full integration testing, debugging, and performance optimizations
- Full serialization of workflows and test results for easy sharing and version control. | +| **August 9 - August 15**
(Week 11) | - Polish UI and ensure responsiveness/accessibility
- Detailed user and developer guides covering installation, usage, and contribution guidelines| +| **August 16 - August 22**
(Week 12) | - Buffer Week | +| **August 25 - September 1**
(Final) | - Final polish, mentor review, and submission | + + +### Benefits to the Community + +APIDash currently focuses on sending requests and inspecting responses. By integrating a testing and automation layer, we unlock powerful use cases: +- **Automated Regression & Integration Testing:** Simplify continuous testing of API endpoints. +- **Collaborative Test Suite Sharing:** Enable teams to share workflows via .json import/export. +- **Native Assertion Engine:** Validate APIs with built-in assertions, eliminating the need for external tools. +- This ecosystem will slash testing time, foster collaboration, and position APIDash as a go-to platform. I’ll support new contributors and enhance features like detailed logs beyond GSoC. + + + +### Future Scope (Beyond GSoC) + +- **Scheduled Test Automation:** + Add support for cron-like scheduled tests for continuous monitoring. +- **Historical Logging:** + Implement a detailed history of test results with trend analytics. +- **CI/CD Integration:** + Explore integration with GitHub Actions or other CI tools for automated testing pipelines. + + +### Final Notes + +I am excited to contribute meaningfully to APIDash by introducing a native, high-performance API testing suite that not only addresses current issues but also lays the groundwork for future enhancements. With full-time commitment, a detailed technical roadmap, and a focus on innovation, I am confident that this project will add significant value to the community and the APIDash ecosystem. + +Looking forward to your feedback and suggestions! diff --git a/doc/proposals/2025/gsoc/application_roshini_api_dash.md b/doc/proposals/2025/gsoc/application_roshini_api_dash.md new file mode 100644 index 00000000..1ae6718e --- /dev/null +++ b/doc/proposals/2025/gsoc/application_roshini_api_dash.md @@ -0,0 +1,153 @@ +# GSoC 2025 Proposal - API Dash +**Applicant**: Roshini D + +--- + +## 📌 About + +- **Full Name**: Roshini D +- **Contact Info**: +91 9449761000 +- **Email**: drroshini16@gmail.com +- **Discord**: rosh09068 +- **GitHub**: [roshcheeku](https://github.com/roshcheeku) +- **LinkedIn**: [Roshini D](https://www.linkedin.com/in/roshini-d-94497525b?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app) +- **Time Zone**: GMT +5:30 (IST) +- **Resume**: [View Resume](https://drive.google.com/file/d/19ZU_qnS_mRASstlQ0PDlReb52By-64Ls/view?usp=drive_link) + +--- + +## 🎓 University Info + +- **University**: BGS College of Engineering and Technology +- **Program**: Bachelor of Engineering, Computer Science and Design +- **Year**: Pre-final Year (3rd Year) +- **Expected Graduation**: May 2026 + +--- + +## 💡 Motivation & Past Experience + +- **FOSS Contributions**: + Yes, contributed to GSSoC (Oct–Nov 2024): + - Tested API endpoints + - Implemented authentication systems + - Authored API documentation + +- **Proud Project**: + **Stock Sentiment Analysis and Prediction (95% accuracy)** + - Combined LSTM deep learning + - Integrated technical indicators and social media sentiment analysis + +- **Motivating Challenges**: + Real-world AI/ML problems with tangible impact, especially integrating multiple data sources and technologies + +- **Availability for GSoC**: + Will balance with Bachelor's program but can dedicate substantial time to GSoC + +- **Mentor Sync Preference**: + Yes, I welcome regular communication for project alignment + +- **Interest in API Dash**: + The mission of simplifying API evaluation resonates with my background in API testing and AI integration + +--- + +## 🔧 Ideas to Improve API Dash + +- Automated batch testing +- Version comparison functionality +- Community benchmark repository +- Framework adapters for easier integration +- Include cost and latency metrics +- A/B testing capabilities + +--- + +## 🧠 Project Proposal: AI API Evaluation Framework + +A robust and extensible platform to evaluate and compare AI APIs from providers such as OpenAI, Google, Anthropic, and others. + +--- + +### 📦 Core Components + +- **Configuration Interface** + UI for input datasets, API credentials, request configs, and metrics + +- **Evaluation Engine** + Processes requests, collects responses, computes metrics + +- **Benchmark Repository** + Stores standard benchmarks for AI tasks, with support for custom benchmarks + +- **Visualization Dashboard** + Charts and tables for comparison results + +- **Batch Processing System** + Enables sequential/parallel evaluations + +--- + +### 🔧 Technical Implementation + +- Adapters for major AI APIs +- Flexible scoring system +- Caching mechanisms +- Exportable reports (PDF, CSV, JSON) +- Extensible architecture + +--- + +### 👩‍💻 User Experience Focus + +- Intuitive end-to-end workflow +- Clear, comparative visualizations +- Granular evaluation metric breakdowns +- Easy sharing and exporting + +--- + +## 🗓️ Weekly Timeline + +### Week 1–2: Research and Planning +- Study existing frameworks and benchmarks +- Define architecture and specs +- Project setup and wireframes + +### Week 3–4: Core Framework Development +- Implement base evaluation engine +- API adapter interfaces +- Data models and testing infra + +### Week 5–6: API Provider Integration +- Adapters for OpenAI, Google, Anthropic +- Auth handling, error/retry mechanisms +- Test API connectivity and parsing + +### Week 7–8: Benchmark Implementation +- Text and sentiment benchmarks +- Image-based benchmarks +- Interface for custom benchmarks + +### Week 9–10: UI Development +- Config interface +- Dashboard visualizations +- Batch UI and settings + +### Week 11–12: Visualization and Reporting +- Comparison graphs +- Drill-down result views +- Export and share features + +### Week 13–14: Testing and Optimization +- Test across APIs and benchmarks +- Performance tuning and caching +- Bug fixing + +### Week 15: Final Polish +- Write user & developer docs +- UI polish and final optimizations +- Final presentation and submission + +--- + diff --git a/doc/proposals/2025/gsoc/application_sakaar_srivastava_authentication.md b/doc/proposals/2025/gsoc/application_sakaar_srivastava_authentication.md new file mode 100644 index 00000000..2d168429 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_sakaar_srivastava_authentication.md @@ -0,0 +1,399 @@ +### About + +1. Full Name: **Sakaar Srivastava** +2. Contact info (email, phone, etc.): **sakaarsri1904@gmail.com** +3. Discord handle: **19doors** +4. GitHub profile link : **https://github.com/19Doors** +5. Twitter, LinkedIn, other socials: **linkedin.com/in/sakaar-srivastava19** +6. Time zone: **Indian Standard Time (IST)** +7. Link to a resume (PDF, publicly accessible via link and not behind any login-wall): **https://drive.google.com/file/d/1uWmwrELFEbITrrUJUCnnQkf6RQJUwvIt/view?usp=drive_link** + +### University Info + +1. University name: **Vellore Institute of Technology** +2. Program you are enrolled in (Degree & Major/Minor): **Bachelor of Technology, Computer Science and Engineering** +3. Year : **3rd year** +5. Expected graduation date: **June-2026** + +### Motivation & Past Experience + +Short answers to the following questions (Add relevant links wherever you can): +1. Have you worked on or contributed to a FOSS project before? Can you attach repo links or relevant PRs? : + **- Yes, I have worked on a FOSS project before. The project is about an AI-powered, cross platform search and command bar designed to make your workflow easier, an open source version of Apple’s Spotlight and better. Link: https://github.com/19Doors/Lumina** + +2. What is your one project/achievement that you are most proud of? Why? + **- One of my good achievements was when I participated in my first hackathon during my second year and won 1st prize among 40+ teams. My team was also ranked among the top 137 teams out of 1Lakh+ teams in Amazon Smbhav Hackathon. These experiences from various hackathons have given me the proper insights on how to function with team members and ensure high efficiency during my second year alone.** [Certificate](https://drive.google.com/file/d/1xpHJfCogZdXbXNs-wfowR_9G0G4tYVOz/view?usp=drive_link) +3. What kind of problems or challenges motivate you the most to solve them? + **- Difficult problems motivate me the most as they challenge my innermost problem solving personality, which keeps me thinking and trying to find a solution for the problem for the whole day, and until I don’t get the solution, my brain never stops thinking.** + + **- Learning new things also motivates me as I like to think that the more skills you gain and apply in the practical world, the more you get to find new and better solutions to old problems.** +4. Will you be working on GSoC full-time? In case not, what will you be studying or working on while working on the project? + **- No, I won't be able to work on GSoC full-time. I have a scheduled internship with Larsen & Toubro from May to July. However, I am deeply enthusiastic about this project and I'm committed to its success. I will dedicate as much time and effort as possible, effectively managing my schedule to ensure I meet all project milestones. I understand the importance of consistent progress and will do whatever I can to deliver exceptional results.** + +5. Do you mind regularly syncing up with the project mentors? + **- No, not at all! Actually, I would love to regularly sync up with the project mentors. Consistent communication and feedback are essential for a successful project, and I believe frequent check-ins will help me stay on track and ensure I'm contributing effectively.** + +6. What interests you the most about API Dash? + **- What I find most appealing about API Dash is its open-source accessibility. Being a student, I've witnessed firsthand the drawbacks of proprietary software such as Postman, most notably the cost restrictions to utilize advanced features. Learning about API Dash through FOSS and understanding its potential to offer a strong, free, and open-source alternative struck a chord with me. The prospect of being part of a project that enables developers, whether or not they have the financial resources, is really exciting. I love open source and think API Dash can become a go-to tool for the community.** +7. Can you mention some areas where the project can be improved? + **- API Dash can be enhanced by adding more API authentication support, making request body options more refined, and making collection management more powerful. UI enhancement via customization and powerful testing features would also benefit greatly.** + +### Project Proposal Information + +1. Proposal Title: **API Authentication Support in API Dash** +2. Abstract: **API Dash currently does not have full support for different types of authentication, which prevents it from being able to communicate with many different APIs. This project rectifies this shortcoming by adding strong support for Basic Authentication, API Key Authentication, Bearer Token Authentication, JWT Bearer Token generation, Digest Auth, OAuth 1.0, and OAuth 2.0. These features will be added to API Dash in a secure and accessible way.** + +*** + +## 3. Detailed Description + +API Dash is a fantastic tool for interacting with APIs, but its current capabilities are somewhat limited when dealing with endpoints that require specific authentication methods. Many modern APIs rely on schemes beyond simple headers for security and authorization. This project aims to significantly enhance API Dash by integrating robust and user-friendly support for a wide range of standard authentication protocols. By implementing Basic Authentication, API Key handling, Bearer Tokens, JWT Bearer generation, Digest Auth, OAuth 1.0, and the versatile OAuth 2.0 framework, we will empower developers to securely and efficiently connect to a much broader spectrum of APIs directly within API Dash. + +### Architectural Approach + +To ensure maintainability, testability, and future extensibility, we'll adopt a modular architecture: + +1. **`AuthenticationStrategy` Interface:** + At the core, we'll define a common Dart interface (let's call it `AuthenticationStrategy`). Every specific authentication method (Basic, API Key, OAuth, etc.) will implement this interface. This ensures consistency and allows API Dash to treat different auth methods polymorphically. Key methods in this interface might include: + * `Future> getHeaders(RequestDetails request)`: Responsible for generating any necessary HTTP headers (like `Authorization`). + * `Future> getQueryParams(RequestDetails request)`: For methods like API Key that might involve adding credentials to query parameters. + * `Future prepareRequest(MutableRequest request)`: A flexible hook to modify the outgoing request object directly before it's sent. This could handle complex scenarios or pre-request token refreshes. + * `Widget buildConfigurationWidget(BuildContext context)`: Each strategy will provide its own specific Flutter widget for user configuration within the API Dash UI. + +2. **Authentication Manager:** + A central service, likely managed using Riverpod (`StateNotifierProvider` seems appropriate), will act as the orchestrator. Its responsibilities will include: + * Storing the currently selected `AuthenticationStrategy` and its associated configuration data for the active request or collection. + * Calling the relevant methods (`getHeaders`, `prepareRequest`, etc.) on the active strategy before an HTTP request is dispatched. + * Managing the state and flow for multi-step processes like OAuth handshakes. + +3. **User Interface Integration:** + We'll introduce a dedicated "Authorization" section or tab within the existing request editor UI. This will feature: + * A clear dropdown or selection mechanism for choosing the desired authentication type. + * A dynamic area that displays the specific configuration widget (`buildConfigurationWidget`) provided by the selected `AuthenticationStrategy`. + +### Detailed Implementation Plan for Each Method + +We will tackle each authentication method systematically: + +#### A. Basic Authentication (#610) + +* **How it Works:** Simple username and password, combined, Base64 encoded, and sent in the `Authorization: Basic ` header. +* **Implementation:** + * **UI:** Input fields for "Username" and "Password" (masked). + * **Logic (`BasicAuthStrategy`):** Use `dart:convert` to perform UTF-8 encoding followed by Base64 encoding. Construct the header value. + * **Conceptual Snippet:** + ```dart + import 'dart:convert'; + + class BasicAuthStrategy implements AuthenticationStrategy { + final String username; + final String password; + // ... constructor ... + + @override + Future> getHeaders(RequestDetails request) async { + final credentials = '$username:$password'; + final encodedCredentials = base64Encode(utf8.encode(credentials)); + return {'Authorization': 'Basic $encodedCredentials'}; + } + // ... other interface methods ... + } + ``` + * **Security:** Emphasize secure storage for the password. + +#### B. API Key Authentication (#611) + +* **How it Works:** A predefined key (and sometimes a value) is sent, either in a specific header or as a query parameter. +* **Implementation:** + * **UI:** Fields for "Key Name" (e.g., `X-API-Key`, `api_key`) and "Key Value". A choice (radio buttons/dropdown) for "Add to Header" or "Add to Query Params". + * **Logic (`ApiKeyStrategy`):** Based on the user's choice, populate either the `getHeaders` or `getQueryParams` map. + * **Conceptual Snippet:** + ```dart + enum ApiKeyLocation { header, query } + + class ApiKeyStrategy implements AuthenticationStrategy { + final String keyName; + final String keyValue; + final ApiKeyLocation addTo; + // ... constructor ... + + @override + Future> getHeaders(RequestDetails request) async { + return (addTo == ApiKeyLocation.header) ? {keyName: keyValue} : {}; + } + + @override + Future> getQueryParams(RequestDetails request) async { + return (addTo == ApiKeyLocation.query) ? {keyName: keyValue} : {}; + } + // ... other interface methods ... + } + ``` + * **Security:** Securely store the API key value. + +#### C. Bearer Token Authentication (#612) + +* **How it Works:** Sends an opaque access token (often, but not always, a JWT) prefixed with "Bearer " in the `Authorization` header. +* **Implementation:** + * **UI:** A primary field for the "Token". An optional field for "Prefix" (defaulting to `Bearer`). + * **Logic (`BearerTokenStrategy`):** Construct the `Authorization` header string. + * **Conceptual Snippet:** + ```dart + class BearerTokenStrategy implements AuthenticationStrategy { + final String token; + final String prefix; // Defaults to 'Bearer' + // ... constructor ... + + @override + Future> getHeaders(RequestDetails request) async { + return {'Authorization': '$prefix $token'}; + } + // ... other interface methods ... + } + ``` + * **Security:** Securely store the token. This strategy often works in conjunction with OAuth 2.0 flows which *obtain* the token. + +#### D. JWT Bearer Token Generation (#613) + +* **How it Works:** Generates a JWT locally based on user configuration, signs it, and then typically sends it using the Bearer Token mechanism. +* **Implementation:** + * **UI:** Fields for "Signing Algorithm" (e.g., HS256, RS256), "Secret" (for HMAC) or "Private Key" (for RSA/ECDSA), JSON editors for "Header Claims" and "Payload Claims", optional "Expiry" duration. + * **Logic (`JwtBearerStrategy`):** + * Integrate a reliable Dart JWT library (e.g., `dart_jsonwebtoken`). + * Parse the JSON claims from the UI. + * Securely retrieve the secret or private key. + * Use the library to sign the JWT with the specified algorithm. + * The generated token will then likely be passed to the `BearerTokenStrategy` for header inclusion. + * **Conceptual Snippet (Illustrative):** + ```dart + import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart'; // Example library + + // Inside JwtBearerStrategy or a dedicated service + String generateAndSignToken(Map payload, Map header, String secretOrKey, SigningAlgorithm alg) { + try { + final jwt = JWT(payload, header: header); + final key = (alg == SigningAlgorithm.HS256) ? SecretKey(secretOrKey) : RsaPrivateKey(secretOrKey); // Simplified example + final token = jwt.sign(key, algorithm: alg, expiresIn: Duration(hours: 1)); // Add expiry logic + return token; + } catch (e) { + // Handle signing errors + print("JWT Signing Error: $e"); + return ''; + } + } + ``` + * **Security:** Secure storage and handling of secrets/private keys are critical. Support for various key formats might be needed. + +#### E. Digest Authentication (#614) + +* **How it Works:** A more secure challenge-response alternative to Basic Auth. Requires two requests. The server challenges with a `nonce`; the client computes a hash using username, password, nonce, realm, URI, etc., and sends it back. +* **Implementation:** + * **UI:** Fields for "Username" and "Password". Algorithm choice might be needed if servers support multiple (e.g., MD5, SHA-256). + * **Logic (`DigestAuthStrategy`):** This requires state management between requests. + 1. Make the initial request. + 2. If a 401 response with `WWW-Authenticate: Digest ...` is received, parse the challenge parameters (nonce, realm, qop, algorithm). + 3. Securely retrieve username/password. + 4. Calculate required hashes (HA1, HA2, response) using `dart:crypto` based on the digest algorithm and parameters provided by the server. + 5. Construct the `Authorization: Digest ...` header containing username, realm, nonce, uri, response hash, cnonce, nc, qop, etc. + 6. The `AuthenticationManager` would need to coordinate resending the *original* request but with the *newly generated* Digest header. This likely involves modifying the request *after* the first attempt fails with a 401 Digest challenge. + +#### F. OAuth 1.0 (#615) + +* **How it Works:** An older, complex protocol involving request signing and multiple steps to obtain access tokens. +* **Implementation:** + * **UI:** Fields for "Consumer Key", "Consumer Secret", "Signature Method" (e.g., HMAC-SHA1), "Callback URL", "Request Token URL", "Authorize URL", "Access Token URL". Potentially fields for storing obtained "Token" and "Token Secret". + * **Logic (`OAuth1Strategy`):** + * Utilize a Dart OAuth 1.0 library if a well-maintained one exists (e.g., `package:oauth1`), otherwise implement the core signing logic. + * Handle the 3-legged flow: Request temporary credentials -> Redirect user for authorization -> Handle callback -> Exchange for access tokens. + * Implement request signing: Construct the base string, generate the signature using the appropriate keys and method, and add the `Authorization: OAuth ...` header with all required parameters (consumer key, token, signature method, signature, timestamp, nonce, version). + +#### G. OAuth 2.0 (#481) + +* **How it Works:** The modern standard, offering various "grant types" for different scenarios. +* **Implementation:** + * **UI:** + * Dropdown for "Grant Type" (Authorization Code, Client Credentials, Resource Owner Password Credentials are common; Implicit is less secure). + * Conditional fields based on grant type: + * *All:* "Access Token URL", "Client ID", "Client Secret", "Scope". + * *Auth Code:* "Authorization URL", "Redirect URI". Add PKCE options (Code Challenge Method: S256/plain, Code Verifier). + * *Password:* "Username", "Password". + * Button: "Get New Access Token" / "Request Authorization". + * Display area for received Access Token, Refresh Token, Expiry. + * **Logic (`OAuth2Strategy` & Manager):** + * **Authorization Code (with PKCE):** + 1. Generate `code_verifier` and `code_challenge`. + 2. Construct Authorization URL (including `response_type=code`, client ID, redirect URI, scope, state, `code_challenge`, `code_challenge_method`). + 3. Launch embedded webview (using `package:webview_flutter` or similar) or external browser to the Authorization URL. + 4. Intercept the redirect to the specified `redirect_uri` to capture the `code` (and `state`). + 5. Make a secure backend POST request to the Access Token URL (`grant_type=authorization_code`, `code`, `redirect_uri`, client ID, client secret, `code_verifier`). + 6. Parse the JSON response for `access_token`, `refresh_token`, `expires_in`. Securely store them. + * **Client Credentials:** Direct POST to Access Token URL (`grant_type=client_credentials`, client ID, client secret, scope). + * **Password Credentials:** Direct POST to Access Token URL (`grant_type=password`, username, password, client ID, client secret, scope). *Use sparingly due to security risks.* + * **Token Handling:** Automatically attach the stored `access_token` (usually as a Bearer token) to subsequent requests. Implement automatic token refresh using the `refresh_token` when an API call returns a 401/unauthorized error potentially due to expiry. + * **Libraries:** Consider using libraries like `package:oauth2_client` or platform-specific interaction packages (`flutter_appauth`) to handle the browser/webview interaction part of the Authorization Code flow. + +### User Interface Design + +The user experience will be streamlined: + +* A distinct "Authorization" tab will be added to the request editing panel. +* A primary dropdown will list all supported authentication types, starting with "No Auth". +* Selecting an auth type will dynamically reveal a tailored configuration panel below it, containing only the necessary fields for that specific method. +* Visual cues will clearly indicate which authentication method is currently active for the request. +* OAuth flows will have dedicated buttons ("Get New Access Token", "Refresh Token") with clear feedback (loading states, success/error messages) during the process. + +### Secure Credential Management + +Security is paramount when handling credentials: + +* We will utilize `package:flutter_secure_storage` as the primary mechanism. This package leverages native secure storage: Keychain on iOS/macOS, Keystore on Android, libsecret on Linux, and Credential Vault on Windows. +* No sensitive information (passwords, secrets, tokens) will ever be stored in plain text in less secure storage like Hive's regular boxes or SharedPreferences. +* UI elements like password fields will be masked. +* Care will be taken to prevent credentials from leaking into application logs during debugging or normal operation. + +### Testing Strategy + +Rigorous testing is essential for authentication features: + +* **Unit Tests:** Each `AuthenticationStrategy` class will have unit tests verifying its core logic (e.g., correct header formatting, Base64 encoding, hash calculations, basic JWT signing logic). Dependencies like secure storage will be mocked. +* **Integration Tests:** + * Mock HTTP servers (using `package:http_mock_adapter` or similar) will simulate API endpoints requiring different authentication methods. + * Tests will cover the full workflow: selecting and configuring an auth method in the UI -> triggering a request -> verifying that the `AuthenticationManager` calls the correct strategy -> asserting that the mock server receives the request with the expected authentication credentials (headers/params). + * Specific integration tests will target the complexities of OAuth flows, mocking the authorization and token endpoints to simulate the handshake. + +### Security Best Practices Adherence + +Throughout development, we will adhere to security best practices: + +* Defaulting to and encouraging HTTPS. +* Implementing secure storage correctly and consistently. +* Sanitizing any user input that forms part of authentication credentials or requests. +* Providing user guidance on secure practices. + +### Documentation + +Clear documentation is vital: + +* The API Dash User Guide will be updated with comprehensive sections explaining how to set up, configure, and use each new authentication method. +* Developer-focused documentation within the codebase will explain the `AuthenticationStrategy` interface and the overall authentication architecture, facilitating future contributions. +* Security recommendations will be included for users. + +### Deliverables + +Upon completion, this project will deliver: + +1. Fully implemented and tested Dart classes for Basic, API Key, Bearer Token, JWT Bearer, Digest Auth, OAuth 1.0, and OAuth 2.0 authentication. +2. Seamlessly integrated UI components within API Dash for configuration. +3. Secure credential storage implementation. +4. A comprehensive suite of unit and integration tests. +5. Updated and thorough user and developer documentation. + +4. Weekly Timeline: A rough week-wise timeline of activities that you would undertake. + +**4. Weekly Timeline:** +**(Coding Period - 12 Weeks)** + +* **Week 1: Foundation & Basic Auth** + * **Goal:** Implement the core authentication manager and the first simple method. + * **Activities:** + * Solidify the `AuthenticationManager` Riverpod provider. + * Integrate `flutter_secure_storage` for basic secure saving/loading of credentials (create helper functions/service). + * Implement the `BasicAuthStrategy` class and its logic. + * Develop the UI panel for configuring Basic Authentication (username, masked password fields). + * Integrate the Basic Auth UI into the main request editor's authorization section. + * Write unit tests for `BasicAuthStrategy` logic. + +* **Week 2: API Key & Bearer Token** + * **Goal:** Implement two more common and relatively straightforward methods. + * **Activities:** + * Implement the `ApiKeyStrategy` class (handling both header and query param options). + * Develop the UI panel for API Key configuration. + * Implement the `BearerTokenStrategy` class. + * Develop the UI panel for Bearer Token configuration. + * Write unit tests for both strategies. + * Start setting up basic integration tests using mock HTTP servers to verify header/param injection. + +* **Week 3: JWT Bearer Generation** + * **Goal:** Implement local JWT generation and signing. + * **Activities:** + * Integrate the chosen Dart JWT library (e.g., `dart_jsonwebtoken`). + * Implement the `JwtBearerStrategy` class, focusing on the token generation logic based on UI inputs. + * Develop the UI panel for JWT configuration (algorithms, claims editors, secret/key input - ensure secure handling in UI). + * Connect the generated JWT to the `BearerTokenStrategy` flow. + * Write unit tests for the JWT generation and signing logic. + +* **Week 4: Digest Auth - Part 1 (Challenge Parsing & Hashing)** + * **Goal:** Tackle the initial complexity of Digest Auth. + * **Activities:** + * Implement logic to parse the `WWW-Authenticate: Digest ...` header received in a 401 response. + * Implement the core hashing functions (HA1, HA2, response) using `dart:crypto` based on parsed parameters. + * Develop the UI panel for Digest Auth configuration (username, password). + * Structure the state management needed within the `AuthenticationManager` to handle the two-step process. + +* **Week 5: Digest Auth - Part 2 (Completion & Testing)** + * **Goal:** Finalize Digest Auth flow and testing. + * **Activities:** + * Implement the logic to construct the `Authorization: Digest ...` header. + * Integrate the request resend mechanism (likely coordinated by the `AuthenticationManager`). + * Write unit tests covering hash calculations and state transitions. + * Write integration tests using a mock server that sends the 401 Digest challenge and expects the correct authorization header on the second request. + +* **Week 6: OAuth 1.0 - Initial Setup & Signing** + * **Goal:** Begin implementation of the complex OAuth 1.0 protocol. + * **Activities:** + * Evaluate/Integrate a suitable Dart OAuth 1.0 library or implement core request signing logic (base string, signature generation for HMAC-SHA1 initially). + * Implement the basic `OAuth1Strategy` structure. + * Develop the initial UI panel for OAuth 1.0 configuration (consumer keys, secrets, URLs, etc.). + * Write unit tests for the request signing mechanism. + * *Mid-term Checkpoint:* Consolidate progress, ensure existing features are stable, update documentation for completed parts. + +* **(Midterm Evaluation Period)** + +* **Week 7: OAuth 1.0 - Flow & Testing** + * **Goal:** Implement the multi-step OAuth 1.0 flow. + * **Activities:** + * Implement the logic for the 3-legged flow (requesting temporary credentials, handling authorization redirect simulation/mocking, exchanging for access tokens). + * Refine request signing to include access tokens. + * Write more comprehensive unit and integration tests for the flow. + +* **Week 8: OAuth 2.0 - Foundation & Simpler Grants** + * **Goal:** Set up OAuth 2.0 structure and implement non-interactive grant types. + * **Activities:** + * Implement the basic `OAuth2Strategy` structure and integrate with the `AuthenticationManager`. + * Develop the core UI panel for OAuth 2.0, including the Grant Type dropdown and conditional fields. + * Implement the **Client Credentials** grant type flow. + * Implement the **Resource Owner Password Credentials** grant type flow (with UI warnings). + * Write unit tests for these grant flows. + +* **Week 9: OAuth 2.0 - Authorization Code Flow (Part 1)** + * **Goal:** Implement the user-interactive part of the most common OAuth 2.0 flow. + * **Activities:** + * Implement PKCE (Proof Key for Code Exchange) helper functions (`code_verifier`, `code_challenge`). + * Integrate a webview or platform-specific browser launching mechanism. + * Implement logic to construct the Authorization URL and launch the webview/browser. + * Implement logic to intercept and parse the redirect URI to capture the authorization `code`. + +* **Week 10: OAuth 2.0 - Authorization Code Flow (Part 2) & Token Refresh** + * **Goal:** Complete the Auth Code flow and implement token management. + * **Activities:** + * Implement the backend request to exchange the authorization `code` for access/refresh tokens. + * Integrate secure storage for OAuth 2.0 tokens. + * Implement the automatic Refresh Token flow (detect 401, use refresh token, update stored tokens, retry original request). + * Thoroughly test the complete Authorization Code and Refresh Token flows using mock servers. + +* **Week 11: Comprehensive Testing & Refinement** + * **Goal:** Ensure robustness and address edge cases across all methods. + * **Activities:** + * Focus heavily on writing comprehensive integration tests for all implemented authentication flows. + * Test various scenarios: invalid credentials, expired tokens, network errors during OAuth flows, different server configurations. + * Refine the UI/UX based on testing and usability feedback. Address any inconsistencies. + * Review and improve error handling and user feedback messages. + +* **Week 12: Documentation, Polish & Final Submission Prep** + * **Goal:** Finalize the project deliverables. + * **Activities:** + * Write detailed user documentation for configuring and using each authentication method in the API Dash User Guide. + * Finalize developer documentation within the code (comments, explaining the architecture). + * Perform final code cleanup, refactoring, and address any remaining TODOs. + * Conduct a final round of testing. + * Prepare the final code submission and project summary report for GSoC. diff --git a/doc/proposals/2025/gsoc/application_udhay_adithya_dashbot.md b/doc/proposals/2025/gsoc/application_udhay_adithya_dashbot.md index a3a5b1a4..5dcb43a0 100644 --- a/doc/proposals/2025/gsoc/application_udhay_adithya_dashbot.md +++ b/doc/proposals/2025/gsoc/application_udhay_adithya_dashbot.md @@ -260,7 +260,7 @@ This milestone will involve running benchmark evaluations for all LLM providers #### **Milestone #4: API Authentication Methods** -This milestone will a new section in the home page of API Dash "Authorization" where users can perform various API Authentication Methods such as, +This milestone will add a new tab "Authorization" in the home page of API Dash where users can perform various API Authentication Methods such as, - Basic authentication - API Auth - API key @@ -268,7 +268,7 @@ This milestone will a new section in the home page of API Dash "Authorization" w - JWT Bearer - Digest Auth - OAuth 1.0 -- OAuth 2.0. +- OAuth 2.0 ## **[GSOC 2025 TIMELINE](https://developers.google.com/open-source/gsoc/timeline) FOR REFERENCE** diff --git a/doc/proposals/2025/gsoc/application_ui designer_Janavi Mahadik.md b/doc/proposals/2025/gsoc/application_ui designer_Janavi Mahadik.md new file mode 100644 index 00000000..15ba4153 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_ui designer_Janavi Mahadik.md @@ -0,0 +1,91 @@ +### About + +1. *Full Name:* Janavi Mahadik +2. *Contact info:* janavimahadik06@gmail.com 9136344543 +3. *Discord handle:* janavimahadik_15736 +4. *GitHub profile link:* https://github.com/JanaviMahadik +5. *LinkedIn:* https://www.linkedin.com/in/janavi-mahadik-b8054b24b/ +6. *Hackerrank:* https://www.hackerrank.com/profile/janavimahadik06 +7. *Leetcode:* https://leetcode.com/u/janavimahadik/ +8. *Time zone:* IST (UTC +5:30) +9. *Link to a resume:* https://drive.google.com/file/d/1UvCNjcUxiyXia7crq_Hm0esl1UPQ5IoV/view?usp=drive_link + + + +### University Info + +1. *University name:* University of Mumbai, SVKM’s Mithibai College +2. *Program:* Bachelor of Computer Science +3. *Year:* Final Year +4. *Expected graduation date:* May 2025 + + + +### Motivation & Past Experience + +1. *Have you worked on or contributed to a FOSS project before?* + While I haven’t contributed to any major public FOSS project yet, I have built full-stack projects like Khanawal (my own project) and + participated in hackathons and collaborative academic projects which follow open-source development practices. + I am eager to contribute meaningfully to real-world open-source projects like API Dash. + +2. *What is your one project/achievement that you are most proud of? Why?* + I’m most proud of Khanawal, a full-stack food ordering and management system that I built independently using Flutter, React.js, Node.js, Express, MongoDB, and Firebase. + It gave me real-world experience in integrating frontends, backends, and databases using REST APIs, and taught me how to manage user roles, build UIs, and implement analytics. + +3. *What kind of problems or challenges motivate you the most to solve them?* + I enjoy solving challenges that bridge the gap between complex backend data and meaningful user interfaces—especially when it improves user experience and productivity. + Problems involving automation, visualization, or data interaction excite me the most. + +4. *Will you be working on GSoC full-time? In case not, what will you be studying or working on while working on the project?* + Yes, I will be available full-time during the GSoC period. While I will have regular college hours, I will ensure uninterrupted availability for project work and mentor sync-ups, + dedicating the required hours per week. + +5. *Do you mind regularly syncing up with the project mentors?* + Not at all! Regular communication helps align goals and expectations, and I am happy to schedule sync-ups, demos, or progress reports. + +6. *What interests you the most about API Dash?* + The idea of turning raw API responses into interactive, customizable UI elements excites me. It aligns well with my experience in full-stack development and my interest in combining backend logic + with intuitive frontends. I’m also excited to work with Flutter and real-time rendering tools. + +7. *Can you mention some areas where the project can be improved?* + - Introducing support for both JSON and XML parsing can increase compatibility. + - Providing a visual drag-and-drop UI builder could enhance the user experience. + - Integrating export templates for popular frameworks (e.g., React, Flutter widgets) can help with faster integration into apps. + - Adding version control for UI snapshots or generated components could make the system more developer-friendly. + + + + +### Project Proposal Information + +1. *Proposal Title:* AI UI Designer for APIs – Dynamic UI Generator from API Responses + +2. *Abstract:* + This project aims to develop an AI-powered agent that automatically generates dynamic, user-friendly UI components from structured API responses (JSON/XML). + By analyzing the API structure, the agent will create UI elements such as tables, forms, charts, and cards, which users can customize and export into their Flutter/Web apps. + This eliminates manual UI coding and enhances the developer workflow. + +3. *Detailed Description:* + The system will accept API endpoints and parse the response structure (JSON/XML). Based on the data types and patterns, the agent will use AI-based heuristics and predefined rules to + create appropriate UI components: + - Lists/tables for arrays of objects + - Input forms for structured fields + - Graphs for numerical trends + - Cards for object summaries + Users will have customization options to change styles, rearrange components, apply filters, pagination, and sorting. The generated UI will be exportable as code (Flutter widgets, HTML/CSS/JS for web apps) + for seamless integration. A real-time previewer will also be included for live editing and visualization. + +4. *Weekly Timeline:* +| Week | Goals / Activities | Deliverables | +|--------|--------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------| +| Week 1 | Community bonding, understand the API Dash codebase and architecture, set up development environment | Local setup ready, active communication with mentors and community | +| Week 2 | Develop core parser to analyze JSON/XML API responses and begin dynamic mapping to UI components | Basic JSON/XML structure parser with object-type identification | +| Week 3 | Implement automatic UI component generation (cards, tables, forms) with real-time API integration | Initial auto-generated UI layout rendering from sample API response | +| Week 4 | Add interactivity features: filters, sorting, pagination; begin frontend-export setup | Dynamic UI components with interactivity; partial export code for web/flutter | +| Week 5 | Improve customization options: themes, layout, component styling | Customization interface; multiple layout templates with applied themes | +| Week 6 | Refactor and modularize code; integrate generated components into existing API Dash system | Seamless integration with API Dash interface; improved code structure | +| Week 7 | Extend support for complex/nested API response structures; maintain tests and benchmarks regularly | Robust UI generation for advanced responses; test coverage updates | +| Week 8 | Improve export functionality with advanced options for Flutter/Web; validate with multiple frameworks | Finalized export feature with support for multiple frameworks | +| Week 9 | Integrate with existing API Dash features; fix bugs and address feedback from mentors and users | Stable version integrated into API Dash; resolved issues based on iterative feedback | +| Week 10| Final polish, optimization, and performance testing; prepare final reports, user guide, and GSoC submission | Optimized, production-ready version with documentation and submission deliverables complete | + diff --git a/doc/proposals/2025/gsoc/application_zabith_fulail_api_dash_feature_improvements.md b/doc/proposals/2025/gsoc/application_zabith_fulail_api_dash_feature_improvements.md new file mode 100644 index 00000000..b2d02d89 --- /dev/null +++ b/doc/proposals/2025/gsoc/application_zabith_fulail_api_dash_feature_improvements.md @@ -0,0 +1,139 @@ +# API Dash - GSoC 2025 Proposal + + +## About + +**Full Name**: Zabith Fulail + +**Contact Info**: mzabith1111@gmail.com , +94 75 256 6446 + +**Discord Handle**: zabithfulalil_47355 + +**GitHub Profile**: [Zabith-Fulail](https://github.com/Zabith-Fulail) + +**LinkedIn**: [Zabith Fulail](https://www.linkedin.com/in/zabith-fulail-434034239/) + +**Time Zone**: GMT+5:30 + +**Resume**: [View PDF](https://drive.google.com/file/d/1rUW0zFdU5tlOSpXMrPQAUKkrkVuq3uqF/view?usp=drive_link) + + +## University Info + +- **University name**: University of Westminster +- **Institution name**: Informatics Institute of Technology (IIT | Colombo, Sri Lanka) +- **Degree & Major**: BSc. (Hons) Computer Science +- **Year**: 3rd Year +- **Expected Graduation**: May, 2026 + +## Motivation & Past Experience +**Have you worked on or contributed to a FOSS project before?** +I haven’t contributed to a FOSS project before, but I’m excited to get started. +I see this as a great opportunity to learn, grow as a developer, and contribute to a real-world project with a strong community. + +**What is your one project/achievement that you are most proud of? Why?** +One project I’m most proud of is UbGo, a fintech app currently live on the Play Store. +It’s a secure and user-friendly digital banking solution that enables users to manage their finances with ease. +Key features include fund transfers, QR payments (LankaQR), bill/payee management, onboarding via JustPay, transaction history, and a 360° financial portfolio view. +I worked on this using Flutter, REST APIs, Firebase, and encryption techniques to ensure both functionality and security. + +**What kind of problems or challenges motivate you the most to solve them?** +I’m most motivated by challenges that improve developer experience and make tools more efficient and enjoyable to use. +Things like adding automation, fixing workflow pain points, or simplifying complex tasks really excite me—especially when it helps other devs save time and focus on what actually matters. + +I love working on problems that involve clean design, better usability, and smart features like pre/post-request scripting or JSON validation. +It’s really satisfying to build something that not only works well but also makes someone else’s job easier. +That’s the kind of impact I aim for in every project I take on. + +**Do you mind regularly syncing up with the project mentors?** +Yes, I’m totally fine with that. I think regular check-ins are super important for staying on track and making sure we’re all aligned. + +**Can you mention some areas where the project can be improved?** +The project can be improved by adding support for pre/post-request scripting, enhancing JSON/GraphQL editing, improving OpenAPI/Swagger import/export, expanding content-type support, and integrating environment variables with better UI indicators. + +## Proposal Title +**Next-Gen API Dash: Power Features for Devs** + +## Abstract +This project aims to significantly enhance API Dash by introducing key developer-focused features that streamline API testing and improve overall usability. +The core improvements include support for pre- and post-request scripting, seamless import/export with OpenAPI/Swagger, enhanced JSON and GraphQL editors with syntax validation and beautification, and support for additional content types like application/x-www-form-urlencoded and file uploads. +These upgrades will reduce manual effort, boost productivity, and make API Dash a more powerful and flexible tool for developers. +By improving environment variable handling, UI feedback, and update notifications, the project also strengthens stability and developer experience. This proposal will transform API Dash into a next-gen platform that better meets the evolving needs of modern API workflows. + +## Detailed Description + +API Dash is a lightweight, open-source API testing tool built with Flutter. While it provides a clean interface and essential request features, it currently lacks several advanced capabilities that modern developers expect for efficient API development and debugging. + +This project, titled **"Next-Gen API Dash: Power Features for Devs"**, aims to bridge that gap by introducing scripting support, enhanced request editing, OpenAPI/Swagger import/export functionality, and a better overall developer experience. + +The focus is on streamlining workflows, reducing repetitive tasks, and making the tool more flexible and extensible—ultimately positioning API Dash as a powerful yet accessible alternative to heavyweight API tools. + +--- + +### Key Features + +- **Pre- and Post-Request Scripting** + - Automate request transformations and response handling. + - Dynamically inject authentication tokens, manipulate headers, and chain requests. + +- **OpenAPI/Swagger Import & Export** + - Allow users to import API definitions from OpenAPI/Swagger (JSON/YAML). + - Export request collections into standard OpenAPI specifications for reuse and documentation. + +- **Enhanced JSON and GraphQL Editor** + - Syntax highlighting, beautification, and validation for JSON bodies. + - GraphQL support including fragments, mutations, subscriptions, and schema inspection. + +- **Support for More Content Types** + - Add `application/x-www-form-urlencoded` support. + - Enable file uploads as request bodies. + +- **Environment Variable Support** + - Allow referencing both in-app and OS environment variables in headers and bodies. + - Enable dynamic value injection for flexible request configurations. + +- **Color-Coded Environments** + - Visually distinguish between environments (e.g., Dev, QA, Prod) using color indicators for safety and clarity. + +- **In-App Update Notifications** + - Notify users when a new version is available and provide easy access to update details. + +- **Improved Test Coverage** + - Write widget and integration tests to ensure feature stability. + - Improve maintainability by enforcing test coverage for new functionality. + +--- + +### Tech Stack + +| Area | Technologies & Tools | +|---------------------------|---------------------------------------------------------| +| **Frontend** | Flutter (Dart), Material Design | +| **API Definition** | OpenAPI, Swagger (YAML/JSON parsing) | +| **Code Editor** | CodeMirror or Ace Editor for JSON & GraphQL editing | +| **GraphQL Handling** | GraphQL Parser (Dart), Custom schema tools | +| **Environment Variables** | Dart `Platform.environment`, App-level env handling | +| **Scripting Support** | Dart (for implementing custom scripting engine) | +| **Testing** | Flutter Widget Testing, Integration Testing | +| **Versioning & Updates** | GitHub Releases API, Pubspec metadata parsing | +| **Package Management** | pub.dev (for managing dependencies) | + + + +## Weekly Timeline + +| **Week** | **Task** | +|--------------|-----------------------------------------------------------------------------------------------| +| **Week 1** | Finalize implementation plan, set up dev environment, discuss feature priorities with mentors | +| **Week 2** | Implement pre-request scripting engine with UI for script input and variable handling | +| **Week 3** | Add post-request scripting support and result-based chaining; log script output | +| **Week 4** | Testing and refinement of scripting features; improve sandboxing and error handling | +| **Week 5** | OpenAPI/Swagger import: parse spec files, map endpoints to internal request model | +| **Week 6** | OpenAPI/Swagger export: enable conversion of API Dash requests into valid OpenAPI spec | +| **Week 7** | Add enhanced JSON editor with beautify/minify, validation, and syntax highlighting | +| **Week 8** | Implement GraphQL request editing with query/mutation toggle and basic schema support | +| **Week 9** | Add support for `application/x-www-form-urlencoded` and `multipart/form-data` (file upload) | +| **Week 10** | Environment variable enhancements: referencing in request headers/body, fallback values | +| **Week 11** | Final polish: in-app update checker, UI refinements, cross-platform testing | +| **Week 12** | Final submission: documentation, screencast, address mentor feedback, and bug fixes | + diff --git a/doc/proposals/2025/gsoc/idea_devanshsingh_dashbot.md b/doc/proposals/2025/gsoc/idea_devanshsingh_dashbot.md new file mode 100644 index 00000000..11433277 --- /dev/null +++ b/doc/proposals/2025/gsoc/idea_devanshsingh_dashbot.md @@ -0,0 +1,22 @@ +### Initial Idea Submission + +Full Name: Devansh Singh +University Name: Alliance University +Program you are enrolled in (Degree & Major/Minor): B.Tech in Software Product Engineering +Year: 1st Year +Expected graduation date: 2028 + +Project Title: DashBot - AI Assistant for API Dash +Relevant issues: [https://github.com/foss42/apidash/issues/271](https://github.com/foss42/apidash/issues/271) + +Idea description: +DashBot is an AI-powered assistant embedded within the API Dash interface. The goal is to enhance user productivity and make API interactions more intuitive for developers by adding a chatbot-like UI that can assist with tasks such as generating API request bodies, interpreting responses, explaining headers/status codes, and helping debug errors. + +The assistant would leverage a local or cloud-based LLM (initially using OpenAI API or similar), with future plans to make it pluggable and privacy-respecting. A floating or sidebar interface will house the chatbot, accessible from anywhere in the app. + +**Approach:** +- Add a chatbot UI panel to the app interface. +- Create a service layer to call OpenAI API for intelligent interactions. +- Integrate context-awareness so DashBot can access current API request/response data. +- Allow quick actions like “Generate a request body” or “What does this error mean?” +- Optional: Make DashBot modular and pluggable for self-hosted models in the future. diff --git a/doc/proposals/2025/gsoc/images/Dashflow.png b/doc/proposals/2025/gsoc/images/Dashflow.png new file mode 100644 index 00000000..b1179b2b Binary files /dev/null and b/doc/proposals/2025/gsoc/images/Dashflow.png differ diff --git a/doc/proposals/2025/gsoc/images/Monitors.png b/doc/proposals/2025/gsoc/images/Monitors.png new file mode 100644 index 00000000..3403f4d3 Binary files /dev/null and b/doc/proposals/2025/gsoc/images/Monitors.png differ diff --git a/doc/proposals/2025/gsoc/images/Runner.png b/doc/proposals/2025/gsoc/images/Runner.png new file mode 100644 index 00000000..294cc932 Binary files /dev/null and b/doc/proposals/2025/gsoc/images/Runner.png differ diff --git a/doc/proposals/2025/gsoc/images/api-testing-suite-5.png b/doc/proposals/2025/gsoc/images/api-testing-suite-5.png new file mode 100644 index 00000000..b6064971 Binary files /dev/null and b/doc/proposals/2025/gsoc/images/api-testing-suite-5.png differ diff --git a/doc/proposals/2025/gsoc/images/apiDash.png b/doc/proposals/2025/gsoc/images/apiDash.png new file mode 100644 index 00000000..b67c50a7 Binary files /dev/null and b/doc/proposals/2025/gsoc/images/apiDash.png differ diff --git a/doc/proposals/2025/gsoc/images/collections.png b/doc/proposals/2025/gsoc/images/collections.png new file mode 100644 index 00000000..0e52fcb4 Binary files /dev/null and b/doc/proposals/2025/gsoc/images/collections.png differ diff --git a/lib/codegen/rust/ureq.dart b/lib/codegen/rust/ureq.dart index 0a8a0744..6137f4fc 100644 --- a/lib/codegen/rust/ureq.dart +++ b/lib/codegen/rust/ureq.dart @@ -5,6 +5,9 @@ import 'package:jinja/jinja.dart' as jj; import '../../utils/utils.dart'; class RustUreqCodeGen { + final String kJsonImport = """ +use serde_json::json; +"""; final String kTemplateStart = """ {%- if isFormDataRequest -%} use std::io::Read; @@ -23,14 +26,13 @@ fn main() -> Result<(), ureq::Error> { """; - String kTemplateJson = """ - - let payload = ureq::json!({{body}}); + String kTemplateJson = """\n + let payload = json!({{body}}); """; String kTemplateHeaders = - """\n {% for key, val in headers -%}.set("{{key}}", "{{val}}"){% if not loop.last %}{{ '\n ' }}{% endif %}{%- endfor -%}"""; + """\n {% for key, val in headers -%}.header("{{key}}", "{{val}}"){% if not loop.last %}{{ '\n ' }}{% endif %}{%- endfor -%}"""; String kTemplateFormHeaderContentType = ''' multipart/form-data; boundary={{boundary}}'''; @@ -90,7 +92,7 @@ multipart/form-data; boundary={{boundary}}'''; let payload = build_data_list(form_data_items); """; - String kStringRequestBody = """\n .send_string(payload)?;"""; + String kStringRequestBody = """\n .send(payload)?;"""; String kStringRequestForm = """\n .send_bytes(&payload)?;"""; @@ -100,7 +102,7 @@ multipart/form-data; boundary={{boundary}}'''; final String kStringRequestEnd = """\n println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -117,12 +119,16 @@ multipart/form-data; boundary={{boundary}}'''; String uuid = getNewUuid(); String url = requestModel.url; - var rec = getValidRequestUri( url, requestModel.enabledParams, ); Uri? uri = rec.$1; + var method = requestModel.method; + var requestBody = requestModel.body; + if (requestModel.bodyContentType == ContentType.json && requestBody?.isNotEmpty == true){ + result += kJsonImport; + } if (uri != null) { var templateStartUrl = jj.Template(kTemplateStart); result += templateStartUrl.render({ @@ -130,9 +136,8 @@ multipart/form-data; boundary={{boundary}}'''; 'isFormDataRequest': requestModel.hasFormData, "method": requestModel.method.name.toLowerCase() }); - - var method = requestModel.method; - var requestBody = requestModel.body; + + if (kMethodsWithBody.contains(method) && requestBody != null) { var contentLength = utf8.encode(requestBody).length; if (contentLength > 0) { diff --git a/lib/widgets/editor_json.dart b/lib/widgets/editor_json.dart index 3e4c2425..5c00cb49 100644 --- a/lib/widgets/editor_json.dart +++ b/lib/widgets/editor_json.dart @@ -2,7 +2,7 @@ import 'dart:math' as math; import 'package:apidash_design_system/apidash_design_system.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:json_text_field/json_text_field.dart'; +import 'package:json_field_editor/json_field_editor.dart'; import 'package:apidash/consts.dart'; class JsonTextFieldEditor extends StatefulWidget { @@ -51,7 +51,12 @@ class _JsonTextFieldEditorState extends State { if (widget.initialValue != null) { controller.text = widget.initialValue!; } - controller.formatJson(sortJson: false); + // Below code fixes issue #782 but JSON formatting + // should be manual via beautify button + // Future.delayed(Duration(milliseconds: 50), () { + // controller.formatJson(sortJson: false); + // setState(() {}); + // }); editorFocusNode = FocusNode(debugLabel: "Editor Focus Node"); } @@ -87,7 +92,7 @@ class _JsonTextFieldEditorState extends State { insertTab(); }, }, - child: JsonTextField( + child: JsonField( key: Key(widget.fieldKey), commonTextStyle: kCodeStyle.copyWith( color: Theme.of(context).brightness == Brightness.dark diff --git a/packages/json_field_editor/.gitignore b/packages/json_field_editor/.gitignore new file mode 100644 index 00000000..905cffba --- /dev/null +++ b/packages/json_field_editor/.gitignore @@ -0,0 +1,33 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +build/ +coverage/ +.vscode/ diff --git a/packages/json_field_editor/.pubignore b/packages/json_field_editor/.pubignore new file mode 100644 index 00000000..eeb9cdb0 --- /dev/null +++ b/packages/json_field_editor/.pubignore @@ -0,0 +1,8 @@ +pubspec.lock +melos_json_field_editor.iml +.dart_tool/ +build/ +coverage/ +test/ +asset/ +pubspec_overrides.yaml diff --git a/packages/json_field_editor/CHANGELOG.md b/packages/json_field_editor/CHANGELOG.md new file mode 100644 index 00000000..57e13def --- /dev/null +++ b/packages/json_field_editor/CHANGELOG.md @@ -0,0 +1,3 @@ +## 1.2.0 + +- Initial release. diff --git a/packages/json_field_editor/LICENSE b/packages/json_field_editor/LICENSE new file mode 100644 index 00000000..4f5cedc9 --- /dev/null +++ b/packages/json_field_editor/LICENSE @@ -0,0 +1,225 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Ashita Prasad, Ankit Mahato + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +---------------------------------------------------------------------------- + +MIT License + +Copyright (c) 2023 Antonio Jesús Caballero Encinas + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/json_field_editor/README.md b/packages/json_field_editor/README.md new file mode 100644 index 00000000..2ca7bf1a --- /dev/null +++ b/packages/json_field_editor/README.md @@ -0,0 +1,92 @@ +# json_field_editor + +A comprehensive package designed for editing JSON text directly within a TextField. This tool integrates seamlessly with Flutter, providing a rich and customizable experience for JSON manipulation. + +It is a fork of `json_text_field` which includes various improvements. + +## Key Features + +- **Dynamic JSON Value Highlighting**: Effortlessly distinguish between different JSON elements like keys, strings, numbers, booleans, nulls, and special characters through customizable text styles. +- **Validation and Error Display**: Instantly validates JSON strings, highlighting errors for quick fixes. +- **Intuitive JSON Formatting**: Automatically formats JSON strings for better readability, with options for sorting and custom controllers. +- **Seamless Integration**: Easy to incorporate into existing Flutter projects, requiring no additional platform-specific configurations. + +## Getting Started + +### Adding the Package + +Include `json_field_editor` in your project by adding it as a dependency in your `pubspec.yaml` file. For detailed instructions, visit [Flutter's plugin guide](https://flutter.io/platform-plugins/). + +### Importing the Package + +```dart +import 'package:json_field_editor/json_field_editor.dart'; +``` + +## Basic Usage + +Replace the standard `TextField` widget with `JsonField` to enable JSON editing capabilities. + +```dart +const JsonField(), + +``` + +### Customizable Features + +`JsonField` extends the familiar `TextField` widget, adding unique properties for a tailored JSON editing experience: + +- **Custom Highlight Styles**: Personalize the appearance for different JSON elements: + - `keyHighlightStyle`: Style for JSON keys. + - `stringHighlightStyle`: Style for string values. + - `numberHighlightStyle`: Style for number values. + - `booleanHighlightStyle`: Style for boolean values. + - `nullHighlightStyle`: Style for null values. + - `specialCharacterHighlightStyle`: Style for special characters. + +### Example Configuration + +```dart +JsonField( + keyHighlightStyle: TextStyle(color: Colors.red), + stringHighlightStyle: TextStyle(color: Colors.green), + numberHighlightStyle: TextStyle(color: Colors.blue), + booleanHighlightStyle: TextStyle(color: Colors.yellow), + nullHighlightStyle: TextStyle(color: Colors.purple), + specialCharacterHighlightStyle: TextStyle(color: Colors.orange), +), +``` + +- **Custom Error Styles**: Personalize the appearance for different JSON errors: + + - `errorTextStyle`: Style for JSON errors text. + - `errorContainerDecoration`: Decoration for JSON errors container. + +- **Formatting and Sorting**: Enable or disable automatic formatting and sorting of the JSON string. + + - `isFormatting`: Toggle JSON string formatting. + - `showErrorMessage`: Show or hide error messages. + + ### Controller Usage + +`JsonField` utilizes `JsonTextFieldController`, an enhanced version of `TextEditingController`, with an additional method for JSON formatting and sorting. + +```dart +final JsonTextFieldController controller = JsonTextFieldController(); + +Column( + children: [ + JsonField( + controller: controller, + isFormatting: true, + showErrorMessage: false, + ), + ElevatedButton( + onPressed: () => controller.formatJson(sortJson: true), + child: const Text('Format Json (sort)'), + ), + ], +) +``` + +Explore the complete example in the `example` folder. diff --git a/packages/json_field_editor/analysis_options.yaml b/packages/json_field_editor/analysis_options.yaml new file mode 100644 index 00000000..a5744c1c --- /dev/null +++ b/packages/json_field_editor/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/json_field_editor/example/.gitignore b/packages/json_field_editor/example/.gitignore new file mode 100644 index 00000000..79c113f9 --- /dev/null +++ b/packages/json_field_editor/example/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/json_field_editor/example/README.md b/packages/json_field_editor/example/README.md new file mode 100644 index 00000000..2b3fce4c --- /dev/null +++ b/packages/json_field_editor/example/README.md @@ -0,0 +1,16 @@ +# example + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/packages/json_field_editor/example/analysis_options.yaml b/packages/json_field_editor/example/analysis_options.yaml new file mode 100644 index 00000000..0d290213 --- /dev/null +++ b/packages/json_field_editor/example/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/json_field_editor/example/lib/main.dart b/packages/json_field_editor/example/lib/main.dart new file mode 100644 index 00000000..7edde6f7 --- /dev/null +++ b/packages/json_field_editor/example/lib/main.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; +import 'package:json_field_editor/json_field_editor.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatefulWidget { + const MyApp({super.key}); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State { + final controller = JsonTextFieldController(); + bool isFormating = true; + + // This widget is the root of your application. + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'Flutter Demo', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: Scaffold( + appBar: AppBar( + title: const Center(child: Text('JSON Text Field Example')), + ), + body: Center( + child: Column( + children: [ + const SizedBox(height: 50), + SizedBox( + width: 300, + height: 300, + child: JsonField( + onError: (error) => debugPrint(error), + showErrorMessage: true, + controller: controller, + isFormatting: isFormating, + keyboardType: TextInputType.multiline, + expands: true, + maxLines: null, + textAlignVertical: TextAlignVertical.top, + onChanged: (value) {}, + decoration: InputDecoration( + hintText: "Enter JSON", + hintStyle: TextStyle( + color: Theme.of( + context, + ).colorScheme.outline.withOpacity(0.6), + ), + focusedBorder: OutlineInputBorder( + borderRadius: const BorderRadius.all(Radius.circular(8)), + borderSide: BorderSide( + color: Theme.of( + context, + ).colorScheme.primary.withOpacity(0.6), + ), + ), + enabledBorder: OutlineInputBorder( + borderRadius: const BorderRadius.all(Radius.circular(8)), + borderSide: BorderSide( + color: Theme.of(context).colorScheme.surfaceVariant, + ), + ), + filled: true, + ), + ), + ), + ElevatedButton( + onPressed: () => controller.formatJson(sortJson: false), + child: const Text('Format JSON'), + ), + ElevatedButton( + onPressed: () => controller.formatJson(sortJson: true), + child: const Text('Format JSON (sort)'), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Format as JSON'), + Switch( + value: isFormating, + onChanged: (value) => setState(() => isFormating = value), + ), + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/packages/json_field_editor/example/pubspec.lock b/packages/json_field_editor/example/pubspec.lock new file mode 100644 index 00000000..e5120c83 --- /dev/null +++ b/packages/json_field_editor/example/pubspec.lock @@ -0,0 +1,236 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 + url: "https://pub.dev" + source: hosted + version: "2.12.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d + url: "https://pub.dev" + source: hosted + version: "1.0.6" + extended_text_field: + dependency: transitive + description: + name: extended_text_field + sha256: "3996195c117c6beb734026a7bc0ba80d7e4e84e4edd4728caa544d8209ab4d7d" + url: "https://pub.dev" + source: hosted + version: "16.0.2" + extended_text_library: + dependency: transitive + description: + name: extended_text_library + sha256: "55d09098ec56fab0d9a8a68950ca0bbf2efa1327937f7cec6af6dfa066234829" + url: "https://pub.dev" + source: hosted + version: "12.0.0" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" + url: "https://pub.dev" + source: hosted + version: "1.3.2" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04 + url: "https://pub.dev" + source: hosted + version: "2.0.3" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + json_field_editor: + dependency: "direct main" + description: + path: ".." + relative: true + source: path + version: "1.2.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec + url: "https://pub.dev" + source: hosted + version: "10.0.8" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" + source: hosted + version: "0.7.4" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" + url: "https://pub.dev" + source: hosted + version: "14.3.1" +sdks: + dart: ">=3.7.0-0 <4.0.0" + flutter: ">=3.24.0" diff --git a/packages/json_field_editor/example/pubspec.yaml b/packages/json_field_editor/example/pubspec.yaml new file mode 100644 index 00000000..4323ca00 --- /dev/null +++ b/packages/json_field_editor/example/pubspec.yaml @@ -0,0 +1,90 @@ +name: example_json_field +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: "none" # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ">=3.2.0 <4.0.0" + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + json_field_editor: + path: ../ + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/json_field_editor/example/pubspec_overrides.yaml b/packages/json_field_editor/example/pubspec_overrides.yaml new file mode 100644 index 00000000..6cf4f951 --- /dev/null +++ b/packages/json_field_editor/example/pubspec_overrides.yaml @@ -0,0 +1,4 @@ +# melos_managed_dependency_overrides: json_field_editor +dependency_overrides: + json_field_editor: + path: .. diff --git a/packages/json_field_editor/lib/json_field_editor.dart b/packages/json_field_editor/lib/json_field_editor.dart new file mode 100644 index 00000000..9489d457 --- /dev/null +++ b/packages/json_field_editor/lib/json_field_editor.dart @@ -0,0 +1,4 @@ +library json_field_editor; + +export 'src/json_field.dart'; +export 'src/json_text_field_controller.dart'; diff --git a/packages/json_field_editor/lib/src/error_message_container.dart b/packages/json_field_editor/lib/src/error_message_container.dart new file mode 100644 index 00000000..7160bdae --- /dev/null +++ b/packages/json_field_editor/lib/src/error_message_container.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; + +class ErrorMessageContainer extends StatelessWidget { + const ErrorMessageContainer({ + super.key, + required this.jsonError, + required this.errorTextStyle, + this.decoration, + }); + + final String? jsonError; + final TextStyle errorTextStyle; + final BoxDecoration? decoration; + + @override + Widget build(BuildContext context) { + return AnimatedSwitcher( + duration: const Duration(milliseconds: 400), + child: + jsonError == null + ? const SizedBox.shrink() + : Container( + width: double.infinity, + padding: const EdgeInsets.all(8), + constraints: const BoxConstraints(minHeight: 40, maxHeight: 60), + decoration: decoration, + child: Center( + child: Text( + jsonError ?? '', + style: const TextStyle(color: Colors.red), + ), + ), + ), + ); + } +} diff --git a/packages/json_field_editor/lib/src/extensions/text_editing_controller_extension.dart b/packages/json_field_editor/lib/src/extensions/text_editing_controller_extension.dart new file mode 100644 index 00000000..a98fae66 --- /dev/null +++ b/packages/json_field_editor/lib/src/extensions/text_editing_controller_extension.dart @@ -0,0 +1,18 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +extension TextEditingControllerExtension on TextEditingController { + void insert(String string) { + int offset = math.min(selection.baseOffset, selection.extentOffset); + String text = + this.text.substring(0, offset) + string + this.text.substring(offset); + value = TextEditingValue( + text: text, + selection: selection.copyWith( + baseOffset: selection.baseOffset + string.length, + extentOffset: selection.extentOffset + string.length, + ), + ); + } +} diff --git a/packages/json_field_editor/lib/src/json_field.dart b/packages/json_field_editor/lib/src/json_field.dart new file mode 100644 index 00000000..8cda1005 --- /dev/null +++ b/packages/json_field_editor/lib/src/json_field.dart @@ -0,0 +1,271 @@ +import 'package:extended_text_field/extended_text_field.dart'; +import 'package:flutter/material.dart'; +import 'package:json_field_editor/json_field_editor.dart'; +import 'package:json_field_editor/src/error_message_container.dart'; +import 'package:json_field_editor/src/json_highlight/json_highlight.dart'; +import 'package:json_field_editor/src/json_utils.dart'; + +class JsonField extends ExtendedTextField { + @override + Type get runtimeType => EditableText; + + const JsonField({ + super.key, + super.autocorrect, + super.autofillHints, + super.autofocus, + super.buildCounter, + super.canRequestFocus, + super.clipBehavior, + this.controller, + super.cursorColor, + super.cursorHeight, + super.cursorRadius, + super.cursorWidth, + super.decoration, + super.enableInteractiveSelection, + super.enableSuggestions, + super.expands, + super.focusNode, + super.inputFormatters, + super.keyboardAppearance, + super.keyboardType, + super.maxLength, + super.maxLines, + super.minLines, + super.obscureText, + super.onAppPrivateCommand, + super.onChanged, + super.onEditingComplete, + super.onSubmitted, + super.onTap, + super.readOnly, + super.scrollController, + super.scrollPadding, + super.scrollPhysics, + super.showCursor, + super.smartDashesType, + super.smartQuotesType, + super.style, + super.textAlign, + super.textAlignVertical, + super.textCapitalization, + super.textDirection, + super.textInputAction, + super.toolbarOptions, + super.contentInsertionConfiguration, + super.selectionControls, + super.mouseCursor, + super.dragStartBehavior, + super.cursorOpacityAnimates, + super.enableIMEPersonalizedLearning, + super.enabled, + super.extendedContextMenuBuilder, + super.extendedSpellCheckConfiguration, + super.maxLengthEnforcement, + super.obscuringCharacter, + super.onTapOutside, + super.restorationId, + super.scribbleEnabled, + super.selectionHeightStyle, + super.selectionWidthStyle, + super.strutStyle, + super.undoController, + this.keyHighlightStyle, + this.stringHighlightStyle, + this.numberHighlightStyle, + this.boolHighlightStyle, + this.nullHighlightStyle, + this.specialCharHighlightStyle, + this.errorTextStyle, + this.commonTextStyle, + this.errorContainerDecoration, + this.showErrorMessage = false, + this.isFormatting = true, + this.onError, + }); + + /// If true, the text will be formatted as json. If false, the text field will behave as a normal text field. Default is true. + final bool isFormatting; + + /// TextStyle for the json key. + final TextStyle? keyHighlightStyle; + + /// TextStyle for the json string. + final TextStyle? stringHighlightStyle; + + /// TextStyle for the json number. + final TextStyle? numberHighlightStyle; + + /// TextStyle for the json bool. + final TextStyle? boolHighlightStyle; + + /// TextStyle for the json null. + final TextStyle? nullHighlightStyle; + + /// TextStyle for the json special character. + final TextStyle? specialCharHighlightStyle; + + /// TextStyle for the error message. + final TextStyle? errorTextStyle; + + /// TextStyle for the common text. + final TextStyle? commonTextStyle; + + /// If true, the error message will be shown, at bottom of the text field. Default is false. + final bool showErrorMessage; + + /// Decoration for the error message container. + final BoxDecoration? errorContainerDecoration; + + /// Callback for the error message. + final Function(String?)? onError; + @override + final JsonTextFieldController? controller; + + @override + JsonFieldState createState() { + return JsonFieldState(); + } +} + +class JsonFieldState extends State { + late final JsonTextFieldController controller = + widget.controller ?? JsonTextFieldController(); + late String? jsonError = + controller.text.isEmpty + ? null + : JsonUtils.getJsonParsingError(controller.text); + late TextStyle style = widget.style ?? const TextStyle(); + late final TextStyle keyHighlightStyle = + widget.keyHighlightStyle ?? + style.copyWith( + fontWeight: FontWeight.bold, + color: const Color.fromARGB(255, 68, 143, 255), + ); + late final TextStyle stringHighlightStyle = + widget.stringHighlightStyle ?? style.copyWith(color: Colors.green[900]); + late final TextStyle numberHighlightStyle = + widget.numberHighlightStyle ?? style.copyWith(color: Colors.purple[900]); + late final TextStyle boolHighlightStyle = + widget.boolHighlightStyle ?? + style.copyWith(color: Colors.purple[900], fontWeight: FontWeight.bold); + late final TextStyle nullHighlightStyle = + widget.nullHighlightStyle ?? + style.copyWith(color: Colors.grey[600], fontWeight: FontWeight.bold); + late final TextStyle specialCharHighlightStyle = + widget.specialCharHighlightStyle ?? + style.copyWith(color: Colors.grey[700]); + late final TextStyle errorTextStyle = + widget.errorTextStyle ?? style.copyWith(color: Colors.red); + late final TextStyle commonTextStyle = + widget.commonTextStyle ?? style.copyWith(color: Colors.black); + + @override + void initState() { + controller.text = + (widget.isFormatting && JsonUtils.isValidJson(controller.text)) + ? JsonUtils.getPrettyPrintJson(controller.text) + : controller.text; + + super.initState(); + } + + void _setJsonError(String? error) => setState(() => jsonError = error); + @override + Widget build(BuildContext context) { + return Stack( + alignment: AlignmentDirectional.bottomCenter, + children: [ + ExtendedTextField( + autocorrect: widget.autocorrect, + autofillHints: widget.autofillHints, + autofocus: widget.autofocus, + buildCounter: widget.buildCounter, + canRequestFocus: widget.canRequestFocus, + clipBehavior: widget.clipBehavior, + controller: controller, + cursorColor: widget.cursorColor, + cursorHeight: widget.cursorHeight, + cursorRadius: widget.cursorRadius, + cursorWidth: widget.cursorWidth, + decoration: widget.decoration, + enableInteractiveSelection: widget.enableInteractiveSelection, + enableSuggestions: widget.enableSuggestions, + expands: widget.expands, + focusNode: widget.focusNode, + inputFormatters: widget.inputFormatters, + keyboardAppearance: widget.keyboardAppearance, + keyboardType: widget.keyboardType, + maxLength: widget.maxLength, + maxLines: widget.maxLines, + minLines: widget.minLines, + obscureText: widget.obscureText, + onAppPrivateCommand: widget.onAppPrivateCommand, + onChanged: (value) { + widget.onChanged?.call(value); + if (widget.isFormatting) { + JsonUtils.validateJson( + json: value, + onError: (error) { + _setJsonError(error); + widget.onError?.call(error); + }, + ); + } + }, + onEditingComplete: widget.onEditingComplete, + onSubmitted: widget.onSubmitted, + onTap: widget.onTap, + readOnly: widget.readOnly, + scrollController: widget.scrollController, + scrollPadding: widget.scrollPadding, + scrollPhysics: widget.scrollPhysics, + showCursor: widget.showCursor, + smartDashesType: widget.smartDashesType, + smartQuotesType: widget.smartQuotesType, + specialTextSpanBuilder: JsonHighlight( + boolHighlightStyle: boolHighlightStyle, + keyHighlightStyle: keyHighlightStyle, + nullHighlightStyle: nullHighlightStyle, + numberHighlightStyle: numberHighlightStyle, + specialCharHighlightStyle: stringHighlightStyle, + stringHighlightStyle: stringHighlightStyle, + commonTextStyle: commonTextStyle, + isFormating: widget.isFormatting, + ), + style: widget.style, + textAlign: widget.textAlign, + textAlignVertical: widget.textAlignVertical, + textCapitalization: widget.textCapitalization, + textDirection: widget.textDirection, + textInputAction: widget.textInputAction, + contentInsertionConfiguration: widget.contentInsertionConfiguration, + selectionControls: widget.selectionControls, + mouseCursor: widget.mouseCursor, + dragStartBehavior: widget.dragStartBehavior, + cursorOpacityAnimates: widget.cursorOpacityAnimates, + enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning, + enabled: widget.enabled, + maxLengthEnforcement: widget.maxLengthEnforcement, + obscuringCharacter: widget.obscuringCharacter, + onTapOutside: widget.onTapOutside, + restorationId: widget.restorationId, + scribbleEnabled: widget.scribbleEnabled, + selectionHeightStyle: widget.selectionHeightStyle, + selectionWidthStyle: widget.selectionWidthStyle, + strutStyle: widget.strutStyle, + undoController: widget.undoController, + ), + if (widget.isFormatting && widget.showErrorMessage) + ErrorMessageContainer( + jsonError: jsonError, + errorTextStyle: errorTextStyle, + decoration: + widget.errorContainerDecoration ?? + const BoxDecoration(color: Colors.amber), + ), + ], + ); + } +} diff --git a/packages/json_field_editor/lib/src/json_highlight/highlight_strategy.dart b/packages/json_field_editor/lib/src/json_highlight/highlight_strategy.dart new file mode 100644 index 00000000..caf32051 --- /dev/null +++ b/packages/json_field_editor/lib/src/json_highlight/highlight_strategy.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; + +abstract class HighlightStrategy { + final TextStyle? textStyle; + + HighlightStrategy({required this.textStyle}); + + bool match(String word); + + TextSpan textSpan(String word); +} + +class KeyHighlightStrategy extends HighlightStrategy { + KeyHighlightStrategy({required super.textStyle}); + + @override + bool match(String word) => RegExp(r'\".*?\"\s*:').hasMatch(word); + + @override + TextSpan textSpan(String word) => TextSpan(text: word, style: textStyle); +} + +class StringHighlightStrategy extends HighlightStrategy { + StringHighlightStrategy({required super.textStyle}); + + @override + bool match(String word) => RegExp(r'\".*?\"').hasMatch(word); + + @override + TextSpan textSpan(String word) => TextSpan(text: word, style: textStyle); +} + +class NumberHighlightStrategy extends HighlightStrategy { + NumberHighlightStrategy({required super.textStyle}); + + @override + bool match(String word) => RegExp(r'\s*\b(\d+(\.\d+)?)\b').hasMatch(word); + + @override + TextSpan textSpan(String word) => TextSpan(text: word, style: textStyle); +} + +class BoolHighlightStrategy extends HighlightStrategy { + BoolHighlightStrategy({required super.textStyle}); + + @override + bool match(String word) => RegExp(r'\b(true|false)\b').hasMatch(word); + + @override + TextSpan textSpan(String word) => TextSpan(text: word, style: textStyle); +} + +class NullHighlightStrategy extends HighlightStrategy { + NullHighlightStrategy({required super.textStyle}); + + @override + bool match(String word) => RegExp(r'\bnull\b').hasMatch(word); + + @override + TextSpan textSpan(String word) => TextSpan(text: word, style: textStyle); +} + +class SpecialCharHighlightStrategy extends HighlightStrategy { + SpecialCharHighlightStrategy({required super.textStyle}); + + @override + bool match(String word) => RegExp(r'[{}\[\],:]').hasMatch(word); + + @override + TextSpan textSpan(String word) => TextSpan(text: word, style: textStyle); +} diff --git a/packages/json_field_editor/lib/src/json_highlight/json_highlight.dart b/packages/json_field_editor/lib/src/json_highlight/json_highlight.dart new file mode 100644 index 00000000..3b61073e --- /dev/null +++ b/packages/json_field_editor/lib/src/json_highlight/json_highlight.dart @@ -0,0 +1,79 @@ +import 'package:extended_text_field/extended_text_field.dart'; +import 'package:flutter/material.dart'; +import 'package:json_field_editor/src/json_highlight/highlight_strategy.dart'; + +class JsonHighlight extends SpecialTextSpanBuilder { + final TextStyle? keyHighlightStyle; + final TextStyle? stringHighlightStyle; + final TextStyle? numberHighlightStyle; + final TextStyle? boolHighlightStyle; + final TextStyle? nullHighlightStyle; + final TextStyle? specialCharHighlightStyle; + final TextStyle? commonTextStyle; + final bool isFormating; + + JsonHighlight({ + this.keyHighlightStyle, + this.stringHighlightStyle, + this.numberHighlightStyle, + this.boolHighlightStyle, + this.nullHighlightStyle, + this.specialCharHighlightStyle, + this.commonTextStyle, + required this.isFormating, + }); + + @override + TextSpan build( + String data, { + TextStyle? textStyle, + SpecialTextGestureTapCallback? onTap, + }) { + List strategies = [ + KeyHighlightStrategy(textStyle: keyHighlightStyle), + StringHighlightStrategy(textStyle: stringHighlightStyle), + NumberHighlightStrategy(textStyle: numberHighlightStyle), + BoolHighlightStrategy(textStyle: boolHighlightStyle), + NullHighlightStrategy(textStyle: nullHighlightStyle), + SpecialCharHighlightStrategy(textStyle: specialCharHighlightStyle), + ]; + + List spans = []; + + data.splitMapJoin( + RegExp( + r'\".*?\"\s*:|\".*?\"|\s*\b(\d+(\.\d+)?)\b|\b(true|false|null)\b|[{}\[\],]', + ), + onMatch: (m) { + String word = m.group(0)!; + if (isFormating) { + spans.add( + strategies + .firstWhere((element) => element.match(word)) + .textSpan(word), + ); + + return ''; + } + spans.add(TextSpan(text: word, style: commonTextStyle)); + return ''; + }, + onNonMatch: (n) { + spans.add(TextSpan(text: n, style: commonTextStyle)); + return ''; + }, + ); + + return TextSpan(children: spans); + } + + @override + SpecialText? createSpecialText( + String flag, { + TextStyle? textStyle, + SpecialTextGestureTapCallback? onTap, + required int index, + }) { + throw UnimplementedError(); + } +} diff --git a/packages/json_field_editor/lib/src/json_text_field_controller.dart b/packages/json_field_editor/lib/src/json_text_field_controller.dart new file mode 100644 index 00000000..2809917a --- /dev/null +++ b/packages/json_field_editor/lib/src/json_text_field_controller.dart @@ -0,0 +1,13 @@ +import 'package:flutter/material.dart'; +import 'package:json_field_editor/src/json_utils.dart'; + +class JsonTextFieldController extends TextEditingController { + JsonTextFieldController(); + + /// Format the JSON text in the controller. Use [sortJson] to sort the JSON keys. + formatJson({required bool sortJson}) { + if (JsonUtils.isValidJson(text)) { + JsonUtils.formatTextFieldJson(sortJson: sortJson, controller: this); + } + } +} diff --git a/packages/json_field_editor/lib/src/json_utils.dart b/packages/json_field_editor/lib/src/json_utils.dart new file mode 100644 index 00000000..ed3e04dc --- /dev/null +++ b/packages/json_field_editor/lib/src/json_utils.dart @@ -0,0 +1,94 @@ +import 'dart:collection'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; + +class JsonUtils { + static bool isValidJson(String? jsonString) { + if (jsonString == null) { + return false; + } + try { + json.decode(jsonString); + return true; + } on FormatException catch (_) { + return false; + } + } + + static String? getJsonParsingError(String? jsonString) { + if (jsonString == null) { + return null; + } + try { + json.decode(jsonString); + + return null; + } on FormatException catch (e) { + return e.message; + } + } + + static String getPrettyPrintJson(String jsonString) { + var jsonObject = json.decode(jsonString); + JsonEncoder encoder = const JsonEncoder.withIndent(' '); + String prettyString = encoder.convert(jsonObject); + return prettyString; + } + + static String getSortJsonString(String jsonString) { + dynamic sort(dynamic value) { + if (value is Map) { + return SplayTreeMap.from( + value.map((key, value) => MapEntry(key, sort(value))), + ); + } else if (value is List) { + return value.map(sort).toList(); + } else { + return value; + } + } + + var jsonObject = json.decode(jsonString); + var sortedMap = sort(jsonObject); + String sortedJsonString = json.encode(sortedMap); + return sortedJsonString; + } + + static void formatTextFieldJson({ + required bool sortJson, + required TextEditingController controller, + }) { + final oldText = controller.text; + final oldSelection = controller.selection; + + controller.text = + sortJson + ? JsonUtils.getPrettyPrintJson( + JsonUtils.getSortJsonString(controller.text), + ) + : JsonUtils.getPrettyPrintJson(controller.text); + + final addedCharacters = controller.text.length - oldText.length; + final newSelectionStart = oldSelection.start + addedCharacters; + final newSelectionEnd = oldSelection.end + addedCharacters; + + controller.selection = TextSelection( + baseOffset: newSelectionStart, + extentOffset: newSelectionEnd, + ); + } + + static validateJson({ + required String json, + required Function(String?) onError, + }) { + if (json.isEmpty) return onError(null); + + if (JsonUtils.isValidJson(json)) { + onError(null); + } else { + onError(JsonUtils.getJsonParsingError(json)); + } + } +} diff --git a/packages/json_field_editor/pubspec.yaml b/packages/json_field_editor/pubspec.yaml new file mode 100644 index 00000000..e2d1ca23 --- /dev/null +++ b/packages/json_field_editor/pubspec.yaml @@ -0,0 +1,23 @@ +name: json_field_editor +description: "JSON field editor allows easy editing of JSON text. Unlock the full capabilities of JSON syntax highlighting, validation & formatting." +version: 1.2.0 +repository: https://github.com/foss42/apidash/tree/main/packages/json_textfield +homepage: https://github.com/foss42/apidash/tree/main/packages/json_textfield +issue_tracker: https://github.com/foss42/apidash/issues +documentation: https://github.com/foss42/apidash/tree/main/packages/json_textfield + +environment: + sdk: ^3.7.0 + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + extended_text_field: ^16.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + +flutter: diff --git a/packages/json_field_editor/test/src/error_message_container_test.dart b/packages/json_field_editor/test/src/error_message_container_test.dart new file mode 100644 index 00000000..57e78421 --- /dev/null +++ b/packages/json_field_editor/test/src/error_message_container_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:json_field_editor/src/error_message_container.dart'; + +void main() { + testWidgets('ErrorMessageContainer shows correct error message', ( + WidgetTester tester, + ) async { + // Build our app and trigger a frame. + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ErrorMessageContainer( + jsonError: 'Test error message', + errorTextStyle: TextStyle(), + ), + ), + ), + ); + + // Verify that our widget shows the correct error message. + expect(find.text('Test error message'), findsOneWidget); + }); + + testWidgets( + 'ErrorMessageContainer does not show error message when jsonError is null', + (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ErrorMessageContainer( + jsonError: null, + errorTextStyle: TextStyle(), + ), + ), + ), + ); + + // Verify that our widget does not show an error message. + expect(find.byType(Text), findsNothing); + }, + ); +} diff --git a/packages/json_field_editor/test/src/json_highlight/json_highlight_test.dart b/packages/json_field_editor/test/src/json_highlight/json_highlight_test.dart new file mode 100644 index 00000000..46bef7ac --- /dev/null +++ b/packages/json_field_editor/test/src/json_highlight/json_highlight_test.dart @@ -0,0 +1,26 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:json_field_editor/src/json_highlight/json_highlight.dart'; + +void main() { + group('JsonHighlight', () { + test( + 'build method should create TextSpan with correct number of children', + () { + // Arrange + var jsonHighlight = JsonHighlight(isFormating: true); + var data = + '{"key": "value", "number": 123, "bool": true, "null": null}'; + + // Act + TextSpan result = jsonHighlight.build(data); + + // Assert + expect( + result.children!.length, + 23, + ); // adjust this based on your expected result + }, + ); + }); +} diff --git a/packages/json_field_editor/test/src/json_text_field_editor_test.dart b/packages/json_field_editor/test/src/json_text_field_editor_test.dart new file mode 100644 index 00000000..b88bbce3 --- /dev/null +++ b/packages/json_field_editor/test/src/json_text_field_editor_test.dart @@ -0,0 +1,128 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:json_field_editor/json_field_editor.dart'; + +void main() { + testWidgets('JsonTextField Widget Test. Formatting a valid json', ( + WidgetTester tester, + ) async { + // Build our app and trigger a frame. + final controller = JsonTextFieldController(); + controller.value = const TextEditingValue( + text: '{"key": "value"}', + selection: TextSelection.collapsed(offset: 0), + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 300, + width: 300, + child: JsonField( + key: ValueKey("1"), + isFormatting: true, + controller: controller, + ), + ), + ), + ), + ); + + // Verify that JsonField is present. + expect(find.byKey(ValueKey("1")), findsOneWidget); + expect(controller.text, equals('{\n "key": "value"\n}')); + }); + + testWidgets( + 'JsonField Widget Test. Formatting a valid json using controller', + (WidgetTester tester) async { + // Build our app and trigger a frame. + final controller = JsonTextFieldController(); + controller.value = const TextEditingValue( + text: '{"key": "value"}', + selection: TextSelection.collapsed(offset: 0), + ); + controller.formatJson(sortJson: false); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + height: 300, + width: 300, + child: JsonField( + key: ValueKey("2"), + isFormatting: true, + controller: controller, + ), + ), + ), + ), + ); + + // Verify that JsonField is present. + expect(find.byKey(ValueKey("2")), findsOneWidget); + expect(controller.text, equals('{\n "key": "value"\n}')); + }, + ); + + testWidgets('JsonField Widget Test, invalid Json', ( + WidgetTester tester, + ) async { + final controller = JsonTextFieldController(); + controller.value = const TextEditingValue( + text: '{"key": "value"', + selection: TextSelection.collapsed(offset: 0), + ); + + controller.formatJson(sortJson: false); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: JsonField( + key: ValueKey("3"), + isFormatting: true, + controller: controller, + ), + ), + ), + ); + + // Verify that JsonField is present. + expect(find.byKey(ValueKey("3")), findsOneWidget); + expect(controller.text, equals('{"key": "value"')); + }); + + testWidgets('JsonField Widget Test, in a valid Json', ( + WidgetTester tester, + ) async { + final controller = JsonTextFieldController(); + controller.value = const TextEditingValue( + text: '{"key": "value","anotherKey": "anotherValue","list": [3,2,1]}', + selection: TextSelection.collapsed(offset: 0), + ); + + // Build our app and trigger a frame. + controller.formatJson(sortJson: true); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: JsonField( + key: ValueKey("4"), + isFormatting: true, + controller: controller, + ), + ), + ), + ); + + // Verify that JsonField is present. + expect(find.byKey(ValueKey("4")), findsOneWidget); + expect( + controller.text, + equals( + '{\n "anotherKey": "anotherValue",\n "key": "value",\n "list": [\n 3,\n 2,\n 1\n ]\n}', + ), + ); + }); +} diff --git a/packages/json_field_editor/test/src/json_utils_test.dart b/packages/json_field_editor/test/src/json_utils_test.dart new file mode 100644 index 00000000..5a369fac --- /dev/null +++ b/packages/json_field_editor/test/src/json_utils_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:json_field_editor/src/json_utils.dart'; + +void main() { + group('getJsonParsingError', () { + test('returns error message for invalid JSON', () { + String? invalidJson = '{ "name": "John", "age": 30, }'; + expect(JsonUtils.getJsonParsingError(invalidJson), isNotNull); + }); + + test('returns null for valid JSON', () { + String? validJson = '{ "name": "John", "age": 30 }'; + expect(JsonUtils.getJsonParsingError(validJson), isNull); + }); + }); + + group('validateJson', () { + test('calls onError with null for valid JSON', () { + String validJson = '{ "name": "John", "age": 30 }'; + bool onErrorCalled = false; + JsonUtils.validateJson( + json: validJson, + onError: (error) { + onErrorCalled = true; + expect(error, isNull); + }, + ); + expect(onErrorCalled, isTrue); + }); + + test('calls onError with error message for invalid JSON', () { + String invalidJson = '{ "name": "John", "age": 30, }'; + bool onErrorCalled = false; + JsonUtils.validateJson( + json: invalidJson, + onError: (error) { + onErrorCalled = true; + expect(error, isNotNull); + }, + ); + expect(onErrorCalled, isTrue); + }); + }); +} diff --git a/pubspec.lock b/pubspec.lock index ba47984e..3384355a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -826,6 +826,13 @@ packages: relative: true source: path version: "0.1.2" + json_field_editor: + dependency: "direct main" + description: + path: "packages/json_field_editor" + relative: true + source: path + version: "1.2.0" json_serializable: dependency: "direct dev" description: @@ -834,14 +841,6 @@ packages: url: "https://pub.dev" source: hosted version: "6.9.4" - json_text_field: - dependency: "direct main" - description: - name: json_text_field - sha256: d922cf02d5807c3971d57e1ba5463c68b98650e8913163e7391cdb31c6af3ae4 - url: "https://pub.dev" - source: hosted - version: "1.2.0" just_audio: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index d4c2ae41..00920988 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -37,7 +37,8 @@ dependencies: json_annotation: ^4.9.0 json_explorer: path: packages/json_explorer - json_text_field: ^1.2.0 + json_field_editor: + path: packages/json_field_editor just_audio: ^0.9.46 just_audio_mpv: ^0.1.7 just_audio_windows: ^0.2.0 diff --git a/test/codegen/rust_ureq_codegen_test.dart b/test/codegen/rust_ureq_codegen_test.dart index 8ef0cb69..9bf736b8 100644 --- a/test/codegen/rust_ureq_codegen_test.dart +++ b/test/codegen/rust_ureq_codegen_test.dart @@ -9,13 +9,14 @@ void main() { group('GET Request', () { test('GET 1', () { - const expectedCode = r"""fn main() -> Result<(), ureq::Error> { + const expectedCode = r""" +fn main() -> Result<(), ureq::Error> { let url = "https://api.apidash.dev"; let response = ureq::get(url) .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -37,7 +38,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -59,7 +60,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -85,7 +86,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -103,11 +104,11 @@ void main() { const expectedCode = r"""fn main() -> Result<(), ureq::Error> { let url = "https://api.github.com/repos/foss42/apidash"; let response = ureq::get(url) - .set("User-Agent", "Test Agent") + .header("User-Agent", "Test Agent") .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -126,11 +127,11 @@ void main() { let url = "https://api.github.com/repos/foss42/apidash"; let response = ureq::get(url) .query("raw", "true") - .set("User-Agent", "Test Agent") + .header("User-Agent", "Test Agent") .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -151,7 +152,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -170,11 +171,11 @@ void main() { let url = "https://api.github.com/repos/foss42/apidash"; let response = ureq::get(url) .query("raw", "true") - .set("User-Agent", "Test Agent") + .header("User-Agent", "Test Agent") .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -197,7 +198,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -215,11 +216,11 @@ void main() { const expectedCode = r"""fn main() -> Result<(), ureq::Error> { let url = "https://api.apidash.dev/humanize/social"; let response = ureq::get(url) - .set("User-Agent", "Test Agent") + .header("User-Agent", "Test Agent") .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -239,11 +240,11 @@ void main() { let response = ureq::get(url) .query("num", "8700000") .query("digits", "3") - .set("User-Agent", "Test Agent") + .header("User-Agent", "Test Agent") .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -264,7 +265,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -287,7 +288,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -308,7 +309,7 @@ void main() { .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -332,11 +333,11 @@ void main() { }"#; let response = ureq::post(url) - .set("content-type", "text/plain") - .send_string(payload)?; + .header("content-type", "text/plain") + .send(payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -351,9 +352,12 @@ void main() { }); test('POST 2', () { - const expectedCode = r'''fn main() -> Result<(), ureq::Error> { + const expectedCode = r''' +use serde_json::json; +fn main() -> Result<(), ureq::Error> { let url = "https://api.apidash.dev/case/lower"; - let payload = ureq::json!({ + + let payload = json!({ "text": "I LOVE Flutter", "flag": null, "male": true, @@ -366,7 +370,7 @@ void main() { .send_json(payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -381,18 +385,21 @@ void main() { }); test('POST 3', () { - const expectedCode = r'''fn main() -> Result<(), ureq::Error> { + const expectedCode = r''' +use serde_json::json; +fn main() -> Result<(), ureq::Error> { let url = "https://api.apidash.dev/case/lower"; - let payload = ureq::json!({ + + let payload = json!({ "text": "I LOVE Flutter" }); let response = ureq::post(url) - .set("User-Agent", "Test Agent") + .header("User-Agent", "Test Agent") .send_json(payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -465,11 +472,11 @@ fn main() -> Result<(), ureq::Error> { let payload = build_data_list(form_data_items); let response = ureq::post(url) - .set("content-type", "multipart/form-data; boundary=test") + .header("content-type", "multipart/form-data; boundary=test") .send_bytes(&payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -542,12 +549,12 @@ fn main() -> Result<(), ureq::Error> { let payload = build_data_list(form_data_items); let response = ureq::post(url) - .set("User-Agent", "Test Agent") - .set("content-type", "multipart/form-data; boundary=test") + .header("User-Agent", "Test Agent") + .header("content-type", "multipart/form-data; boundary=test") .send_bytes(&payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -612,11 +619,11 @@ fn main() -> Result<(), ureq::Error> { let payload = build_data_list(form_data_items); let response = ureq::post(url) - .set("content-type", "multipart/form-data; boundary=test") + .header("content-type", "multipart/form-data; boundary=test") .send_bytes(&payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -681,11 +688,11 @@ fn main() -> Result<(), ureq::Error> { let payload = build_data_list(form_data_items); let response = ureq::post(url) - .set("content-type", "multipart/form-data; boundary=test") + .header("content-type", "multipart/form-data; boundary=test") .send_bytes(&payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -757,11 +764,11 @@ fn main() -> Result<(), ureq::Error> { let response = ureq::post(url) .query("size", "2") .query("len", "3") - .set("content-type", "multipart/form-data; boundary=test") + .header("content-type", "multipart/form-data; boundary=test") .send_bytes(&payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -828,13 +835,13 @@ fn main() -> Result<(), ureq::Error> { let response = ureq::post(url) .query("size", "2") .query("len", "3") - .set("User-Agent", "Test Agent") - .set("Keep-Alive", "true") - .set("content-type", "multipart/form-data; boundary=test") + .header("User-Agent", "Test Agent") + .header("Keep-Alive", "true") + .header("content-type", "multipart/form-data; boundary=test") .send_bytes(&payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -849,9 +856,11 @@ fn main() -> Result<(), ureq::Error> { group('PUT Request', () { test('PUT 1', () { - const expectedCode = r'''fn main() -> Result<(), ureq::Error> { + const expectedCode = r'''use serde_json::json; +fn main() -> Result<(), ureq::Error> { let url = "https://reqres.in/api/users/2"; - let payload = ureq::json!({ + + let payload = json!({ "name": "morpheus", "job": "zion resident" }); @@ -860,7 +869,7 @@ fn main() -> Result<(), ureq::Error> { .send_json(payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -877,9 +886,12 @@ fn main() -> Result<(), ureq::Error> { group('PATCH Request', () { test('PATCH 1', () { - const expectedCode = r'''fn main() -> Result<(), ureq::Error> { + const expectedCode = r''' +use serde_json::json; +fn main() -> Result<(), ureq::Error> { let url = "https://reqres.in/api/users/2"; - let payload = ureq::json!({ + + let payload = json!({ "name": "marfeus", "job": "accountant" }); @@ -888,7 +900,7 @@ fn main() -> Result<(), ureq::Error> { .send_json(payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -905,13 +917,14 @@ fn main() -> Result<(), ureq::Error> { group('DELETE Request', () { test('DELETE 1', () { - const expectedCode = r"""fn main() -> Result<(), ureq::Error> { + const expectedCode = r""" +fn main() -> Result<(), ureq::Error> { let url = "https://reqres.in/api/users/2"; let response = ureq::delete(url) .call()?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) } @@ -926,9 +939,12 @@ fn main() -> Result<(), ureq::Error> { }); test('DELETE 2', () { - const expectedCode = r'''fn main() -> Result<(), ureq::Error> { + const expectedCode = r''' +use serde_json::json; +fn main() -> Result<(), ureq::Error> { let url = "https://reqres.in/api/users/2"; - let payload = ureq::json!({ + + let payload = json!({ "name": "marfeus", "job": "accountant" }); @@ -937,7 +953,7 @@ fn main() -> Result<(), ureq::Error> { .send_json(payload)?; println!("Response Status: {}", response.status()); - println!("Response: {}", response.into_string()?); + println!("Response: {}", response.into_body().read_to_string()?); Ok(()) }