Search code examples
flutterswaggerflutter-http

swagger-codegen in flutter project


I am new to flutter and trying to integration below library for using Swagger in flutter project. https://github.com/swagger-api/swagger-codegen/tree/master/samples/client/petstore/dart/swagger

Steps which i did so far :

1)

added the Path in Pubspec.yaml
     swagger:
        path: /path/swagger-codegen-master/samples/client/petstore/dart/swagger

2) main.dart file :

import 'package:swagger/api.dart';

3) added in Pubspec.yaml for swagger file so my project support SDK 2.0.0

 environment:
      sdk: ">=2.0.0-dev.68.0 <3.0.0"

It is working fine Problem is : I can able to access var api_instance = new PetApi(); Which is swagger api implemented in that. How can i use the url of my swagger api which had complete different API as per my project. For eg on url http://petstore.swagger.io/v2 but on http://student.swagger.io/v2 and have complete different request , header and response parameters ? How can i customise it as per my use.


Solution

  • Here are the steps I followed to link the swagger API files,
    1.Generated the client files for dart using https://editor.swagger.io
    2.Replaced the api_client.dart file's usage of BrowserClient() with IOClient() and imported the required library. This BrowserClient caused a build error in my project because it contains web dependencies

      class ApiClient {
          String basePath;
          var client = new BrowserClient();//old one
          var client = new IOClient();//should be changed to this
    
    .
    .
    


    3.Then Created the client class to access the API's as below,

    /// Singleton class for ApiClient
    class Client {
      ApiClient apiClient;
      AuthApi _authApi;
    
      AuthApi get authApi => _authApi;
      static final Client _client = Client._initClient();
    
      factory Client() {
        return _client;
      }
    
      Client._initClient() {
        apiClient = ApiClient(
          basePath: "http://yourproject.apilink",
        );
        _authApi = AuthApi(apiClient);
      }
    }
    


    4.Then,

    class AuthImpl {
      final Client client;
    
      AuthImpl(this.client) {}
    
      Future<User> signIn({
        @required String deviceID,
        @required String deviceType,
        @required String phone,
        @required String password,
      }) async {
        AuthLoginResponse authLoginResponse;
        User user;
    
        authLoginResponse = await client.authApi
            .authPostLogin(deviceID, deviceType, phone, password);
        user = authLoginResponse.payload;
        return user;
      }}