Creating Swagger UI for Frappe: A Comprehensive Guide

:rocket: Exciting News! :rocket:
I’m thrilled to share a new milestone with our Frappe application: we’ve successfully integrated Swagger UI for API documentation and testing! :tada:

:scroll: What’s New:
Automated Swagger JSON Generation: A Python script now automatically generates Swagger JSON files from our Frappe API endpoints, making documentation more efficient and up-to-date.

Interactive Swagger UI: With a new HTML setup, you can now visualize and interact with our API documentation directly in the browser. This makes testing and exploring endpoints easier than ever.

Example Endpoints: We’ve included examples of POST and GET requests using Frappe and Pydantic, showcasing how to define and validate API requests seamlessly.

:wrench: Why This Matters:
Efficient Documentation: Keep your API docs current and accurate with minimal effort.

Enhanced Testing: Test your APIs interactively via Swagger UI.
Better Collaboration: Clear documentation improves understanding and collaboration among developers and users.
Check out the full guide on how to set up Swagger UI with Frappe in my latest blog post. I’d love to hear your thoughts and feedback!
Happy coding! :computer::sparkles:

frappe #SwaggerUI api documentation #Python #Pydantic #Tech #Development


8 Likes

Hi, @Omkar_Darves

I created the file in the path: /workspace/development/frappe-bench/apps/frappe/frappe/www/swagger.py

Then I created: /workspace/development/frappe-bench/apps/frappe/frappe/www/swagger.html

I added it to hooks.py

website_route_rules += [
{“from_route”: “/swagger.json”, “to_route”: “swagger.json”},
{“from_route”: “/swagger”, “to_route”: “swagger”},
]

And I even created: /workspace/development/frappe-bench/apps/frappe/frappe/api.py

Swagger opens with the following message:

Failed to load API definition.

Errors

Hide

Fetch error

NOT FOUND /swagger.json

And site/swagger.json with error 404

Hi @weldonet you will have to run generate_swagger_json function in swagger.py file, to create a swagger.json and this file should be pointed from the swagger.html

Please let me know the api that you have written. Because in this code snippet I am searching for some functionalities by using that generate_swagger_json function will recognize if particular function is API or not.

Also If you are not in a hurry, I’m planning to release it as an app for better integration.

Sorry for the late reply!

You can now integrate Swagger UI with Frappe apps using my new app. Install it with:

bench get-app https://github.com/omkardarves/swagger

Swagger Generator for Frappe Apps offers:

  • Automatic Swagger UI Generation for API endpoints.
  • Customizable for APIs in the app_name/api folder.
  • Pydantic Model Integration for request bodies.

Setup:

  1. Place your APIs in the app_name/api folder.
  2. In the “Swagger Settings” doctype, click “Generate Swagger JSON.”
  3. Access the Swagger UI via the swagger.html file.

For more details, check the README.md. Let me know if you have any questions!
I have also added it to Frappe Marketplace, it is under review.

6 Likes

Hai @Omkar_Darves During the installation of the Swagger app on my site, I have an error
File “/home/ubuntu/frappe-bench/apps/swagger/swagger/validator.py”, line 1, in
from validator import validate as validate_
ModuleNotFoundError: No module named ‘validator’
ERROR: bench build --app swagger
subprocess.CalledProcessError: Command ‘bench build --app swagger’ returned non-zero exit status 1.
The above exception was the direct cause of the following exception:

pip install -r apps/swagger/requirements.txt

@Omkar_Darves I have installed the Swagger app and configured it on my site. However, I am facing a character limit issue when trying to get the API of my custom apps.

can you tell me how you are defining your apis?
and issue traceback also

We have install CRM application in our Frappe site . They already Defined api in the api folder for that apis we facing the Character limit issuse @Omkar_Darves

This is how your apis should look like to get into swagger documentation.

import swagger
from pydantic import BaseModel

class UserModel(BaseModel):
    email: str
    username: str
    age: int


@frappe.whitelist(allow_guest=True)
@validate_request(UserModel)
def add_user(validated_data: UserModel):
    try:
        swagger.validate_http_method("POST")
        new_user = frappe.get_doc({
            "doctype": "User",
            "email": validated_data.email,
            "username": validated_data.username,
            "first_name": validated_data.username,
            "age": validated_data.age,
        })
        new_user.insert(ignore_permissions=True)
        return {
            "status": "success",
            "message": "User created successfully",
            "data": new_user.as_dict(),
        }
    except Exception as e:
        return {"status": "error", "message": str(e)}

@frappe.whitelist()
def get_customer(cust_code: str):
    try:
        swagger.validate_http_method("GET")
        try:
            customer = frappe.get_doc("Loan Customer", cust_code)
        except DoesNotExistError:
            raise swagger.exceptions.NotFoundException(_("Pincode not found"))
        return swagger.respondWithSuccess(data=customer)
    except swagger.exceptions.APIException as e:
        swagger.log_api_error()
        return e.respond()