cancel
Showing results for 
Search instead for 
Did you mean: 

Swagger-client - Recommended usage/creation of SwaggerClient

SOLVED
Highlighted
Frequent Visitor

Swagger-client - Recommended usage/creation of SwaggerClient

Hi all.

 

I'm completely new to using Swagger, and I'm trying to refactor our React project to use our Swagger schema-generated Spring Boot API. I want to create the SwaggerClient once inside a file (so I don't need to repeat the creation of the SwaggerClient every time with the schema URL) with custom hooks then use async/await to fetch and return the result. Is this an "acceptable" approach or against Swagger's intentions in any way? Resources seem to be very thin on the swagger-client front when I've searched via Google.

 

Something like the following:

// DataHooks.js
const SWAGGER_CLIENT = new SwaggerClient("/path/to/api.json").client;

export function useSwaggerApi() {
    return SWAGGER_CLIENT.apis;
}

export async function useAddFood() {
    const [food, setFood] = useState(null);
    const FOOD_API = useSwaggerApi().food;
    try {
        const response = await FOOD_API.addFoodItem({ requestBody: { ... }});
        setFood(response);
    } catch (error {}
    return food;
}

 

I've logged out the above in a dummy component with the example pets.json to make sure the SwaggerClient resolves and I can see the pets, store etc so it seems to work as expected.

 

Thanks all. I really appreciate your help. 🙂

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
Highlighted
Staff

Re: Swagger-client - Recommended usage/creation of SwaggerClient

Depending on how you need to use SwaggerClient, you may not need to instantiate a new instance of SwaggerClient. Instead, you can import SwaggerClient, then directly access SwaggerClient methods. You can find some examples here: https://github.com/swagger-api/swagger-js/tree/master/docs/usage

 

View solution in original post

1 REPLY 1
Highlighted
Staff

Re: Swagger-client - Recommended usage/creation of SwaggerClient

Depending on how you need to use SwaggerClient, you may not need to instantiate a new instance of SwaggerClient. Instead, you can import SwaggerClient, then directly access SwaggerClient methods. You can find some examples here: https://github.com/swagger-api/swagger-js/tree/master/docs/usage

 

View solution in original post

New Here?
Join us and watch the welcome video:
Announcements
Top Kudoed Authors