Repository: microsoft/kiota (csharp)

Issue:
Error from Users sample code SEARCH USER BY NAME 

This sample code is from **user_samples.md**

When I run it, I get this error :

    **request_configuration =  UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(  query_parameters=query_params, )
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'UsersRequestBuilder' has no attribute 'UsersRequestBuilderGetRequestConfiguration'**

I am using python 3.12 and msgraph-sdk version  1.3.0.

Any idea what is causing this?  

Is it the version of the msgraph-sdk old?  This came from pypi.





```
import asyncio

from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder


async def find_user(user_name: str, client: GraphServiceClient) -> None:
    # The query used here is the same when searching for users in Azure AD via web console
    query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
        search=[
            f'("displayName:{user_name}" OR "mail:{user_name}" OR "userPrincipalName:{user_name}" OR "givenName:{user_name}" OR "surName:{user_name}" OR "otherMails:{user_name}")'
        ],
    )
    request_configuration = (  UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(  query_parameters=query_params, ) 
   )
    
    request_configuration.headers.add("ConsistencyLevel", "eventual")

    response = await client.users.get(request_configuration=request_configuration)
    if response.value:
        user = response.value[0]
        print(
            f"Found user for {user_name} in the Azure AD with user principal name {user.user_principal_name} and display name {user.display_name}"
        )
    else:
        print(f"{user_name} user in the Azure AD not found")


def main():
    # Use cli credentials to authenticate against Azure
    # Before running script do `az login`
    #credential = AzureCliCredential()

    SP_CLIENT_ID='yyyy'
    SP_TENANT_ID='zzzzz'
    SP_SECRET='xxx'  

    scopes = ['https://graph.microsoft.com/.default']
    credential = ClientSecretCredential(SP_TENANT_ID,
                                   SP_CLIENT_ID,
                                    SP_SECRET)

    client = GraphServiceClient(credentials=credential, scopes=scopes)
    asyncio.run(find_user("stuartp", client))


main()
```

Pull request:
Closes https://github.com/microsoft/kiota/issues/4535
Closes https://github.com/microsoft/kiota/issues/4507
Closes https://github.com/microsoftgraph/msgraph-sdk-python/issues/673
Closes https://github.com/microsoftgraph/msgraph-sdk-python/issues/671
Closes 

**Before**:
Available:
```python
    async def get(self,request_configuration: Optional[GroupsRequestBuilderGetRequestConfiguration] = None) -> Optional[GroupCollectionResponse]:
```
Desired
```python
+from kiota_abstractions.base_request_configuration import RequestConfiguration

+request_configuration = RequestConfiguration(
query_parameters = query_params,
)
```

**After this PR**

```python
    def to_get_request_information(self,request_configuration: Optional[RequestConfiguration[GroupsRequestBuilderGetQueryParameters]] = None) -> RequestInformation:
```



**Before**:

```python
    async def post(self,body: Optional[Group] = None, request_configuration: Optional[GroupsRequestBuilderPostRequestConfiguration] = None) -> Optional[Group]:
```

**After this PR:**
```python
    def to_post_request_information(self,body: Group, request_configuration: Optional[RequestConfiguration[QueryParameters]] = None) -> RequestInformation:
```

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3386f8429c..7fa099376b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 - Aligns naming of sliced OpenAPI description generated by `plugin add` should be named `<plugin-name>-openapi.json|yml` [#4595](https://github.com/microsoft/kiota/issues/4595)
 - Fixed RPC server to respect the `KIOTA_CONFIG_PREVIEW` flag.
 - Fixed handling of nested arrays to be handled as `UntypedNode` instances [#4549](https://github.com/microsoft/kiota/issues/4549)
-- Fixed `InvalidOperationException` thrown when serializing IBacked models with no changes present in the additional data in dotnet [microsoftgraph/msgraph-sdk-dotnet#2471](https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/2471). 
+- Fixed `InvalidOperationException` thrown when serializing IBacked models with no changes present in the additional data in dotnet [microsoftgraph/msgraph-sdk-dotnet#2471](https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/2471).
+- Fixed `RequestConfiguration` Classes dropped in RequestBuilder methods in python [#4535](https://github.com/microsoft/kiota/issues/4535)
+- Fixed incorrect optional types in method parameters in Python [#4507](https://github.com/microsoft/kiota/issues/4507)
 
 ## [1.14.0] - 2024-05-02
 
@@ -1329,4 +1331,3 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 ### Added
 
 - Initial GitHub release
-
diff --git a/src/Kiota.Builder/Refiners/PythonRefiner.cs b/src/Kiota.Builder/Refiners/PythonRefiner.cs
index 5c8278dc35..01d54a9fdd 100644
--- a/src/Kiota.Builder/Refiners/PythonRefiner.cs
+++ b/src/Kiota.Builder/Refiners/PythonRefiner.cs
@@ -46,7 +46,8 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
                 static x => x.ToSnakeCase(),
                 GenerationLanguage.Python);
             RemoveCancellationParameter(generatedCode);
-            RemoveRequestConfigurationClasses(generatedCode,
+            RemoveRequestConfigurationClasses(
+                generatedCode,
                 new CodeUsing
                 {
                     Name = "RequestConfiguration",
@@ -60,7 +61,10 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
                 {
                     Name = "QueryParameters",
                     IsExternal = true,
-                });
+                },
+                keepRequestConfigurationClass: true,
+                addDeprecation: true
+            );
             AddDefaultImports(generatedCode, defaultUsingEvaluators);
             CorrectCoreType(generatedCode, CorrectMethodType, CorrectPropertyType, CorrectImplements);
             cancellationToken.ThrowIfCancellationRequested();
@@ -169,6 +173,8 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
             $"{AbstractionsPackageName}.request_information", "RequestInformation"),
         new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.RequestGenerator),
             $"{AbstractionsPackageName}.request_option", "RequestOption"),
+        new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.RequestGenerator),
+            $"{AbstractionsPackageName}.default_query_parameters", "QueryParameters"),
         new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.Serializer),
             SerializationModuleName, "SerializationWriter"),
         new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.Deserializer),
diff --git a/src/Kiota.Builder/Writers/Python/PythonConventionService.cs b/src/Kiota.Builder/Writers/Python/PythonConventionService.cs
index 2ff655901d..1dd3370bb1 100644
--- a/src/Kiota.Builder/Writers/Python/PythonConventionService.cs
+++ b/src/Kiota.Builder/Writers/Python/PythonConventionService.cs
@@ -56,7 +56,7 @@ public override string GetParameterSignature(CodeParameter parameter, CodeElemen
         var defaultValueSuffix = string.IsNullOrEmpty(parameter.DefaultValue) ? string.Empty : $" = {parameter.DefaultValue}";
         var deprecationInfo = GetDeprecationInformation(parameter);
         var deprecationSuffix = string.IsNullOrEmpty(deprecationInfo) ? string.Empty : $"# {deprecationInfo}";
-        return $"{parameter.Name}: {(parameter.Type.IsNullable ? "Optional[" : string.Empty)}{GetTypeString(parameter.Type, targetElement, true, writer)}{(parameter.Type.IsNullable ? "] = None" : string.Empty)}{defaultValueSuffix}{deprecationSuffix}";
+        return $"{parameter.Name}: {(parameter.Optional ? "Optional[" : string.Empty)}{GetTypeString(parameter.Type, targetElement, true, writer)}{(parameter.Optional ? "] = None" : string.Empty)}{defaultValueSuffix}{deprecationSuffix}";
     }
     private static string GetTypeAlias(CodeType targetType, CodeElement targetElement)
     {
@@ -87,7 +87,9 @@ public override string GetTypeString(CodeTypeBase code, CodeElement targetElemen
                 typeName = targetElement.Parent.Name;
             if (code.ActionOf && writer != null)
                 return WriteInlineDeclaration(currentType, targetElement, writer);
-            return $"{collectionPrefix}{typeName}{collectionSuffix}";
+            var genericParameters = currentType.GenericTypeParameterValues.Count != 0 ?
+              $"[{string.Join(", ", currentType.GenericTypeParameterValues.Select(x => GetTypeString(x, targetElement, includeCollectionInformation)))}]" : string.Empty;
+            return $"{collectionPrefix}{typeName}{genericParameters}{collectionSuffix}";
         }
 
         throw new InvalidOperationException($"type of type {code.GetType()} is unknown");


Test patch:
diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs
index fb18a5651e..4bb0166050 100644
--- a/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs
+++ b/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs
@@ -1653,7 +1653,7 @@ public void WritesConstructorForRequestBuilderWithRequestAdapter()
         writer.Write(method);
         var result = tw.ToString();
         Assert.DoesNotContain("super().__init__(self)", result);
-        Assert.Contains("def __init__(self,request_adapter: Optional[RequestAdapter] = None)", result);
+        Assert.Contains("def __init__(self,request_adapter: RequestAdapter)", result);
         Assert.DoesNotContain("This property has a description", result);
         Assert.DoesNotContain($"self.{propName}: Optional[str] = {defaultValue}", result);
         Assert.DoesNotContain("get_path_parameters(", result);
@@ -1716,7 +1716,7 @@ public void WritesConstructorForRequestBuilderWithRequestAdapterAndPathParameter
         writer.Write(method);
         var result = tw.ToString();
         Assert.DoesNotContain("super().__init__(self)", result);
-        Assert.Contains("def __init__(self,request_adapter: Optional[RequestAdapter] = None, path_parameters: Optional[Union[Dict[str, Any], str]] = None,", result);
+        Assert.Contains("def __init__(self,request_adapter: RequestAdapter, path_parameters: Union[Dict[str, Any], str],", result);
         Assert.Contains("username: Optional[str] = None", result);
         Assert.Contains("if isinstance(path_parameters, dict):", result);
         Assert.Contains("path_parameters['username'] = str(username)", result);
@@ -2026,7 +2026,7 @@ public void WritesApiConstructorWithBackingStore()
         tempWriter.SetTextWriter(tw);
         tempWriter.Write(method);
         var result = tw.ToString();
-        Assert.Contains("backing_store: Optional[BackingStoreFactory] = None)", result);
+        Assert.Contains("backing_store: BackingStoreFactory)", result);
         Assert.Contains("self.request_adapter.enable_backing_store(backing_store)", result);
     }
     [Fact]