question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

If the query parameter type is int, an error will be reported if an empty string is passed from the front end

See original GitHub issue
@router.get('/listAll', summary="获取事项内容列表")
async def listAll(
        db: Session = Depends(deps.get_db),
        siteId: int = Depends(deps.setSiteId),
        itemId: int = Query(None, description='事项ID'),
        page: int = Query(1, description='页码'),
        size: int = Query(10, description='条数')
):

GET /listAll?itemId&page=1&size=10

output:

1 validation error for Request
query -> itemId
  value is not a valid integer (type=type_error.integer)

I expect itemid = NONE

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
whiskeyrivercommented, Jul 22, 2021

@Alpha188 Looks like this was brought up in https://github.com/tiangolo/fastapi/issues/1147 previously. The gist is that Starlette keeps empty parameters like this as flag parameters (https://github.com/encode/starlette/issues/860). The code in question is https://github.com/encode/starlette/blob/master/starlette/datastructures.py#L125.

This results in the itemId being passed in as a blank string, rather than the NoneType you might expect:

In [1]: from urllib.parse import parse_qsl
In [2]: parse_qsl("itemId&page=1&size=10", keep_blank_values=True)
Out[3]: [('itemId', ''), ('page', '1'), ('size', '10')]

The quickest way I can think of to get around this would be with a Pydantic custom type (https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types)

from pydantic import validators

class MyCustomInt(int):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="int")

    @classmethod
    def validate(cls, v):
        if v is None or v == "":
            return None
        return validators.int_validator(v)

    def __repr__(self):
        return f"MyCustomInt({super().__repr__()})"


@router.get("/listAll")
async def listAll(
    itemId: Optional[MyCustomInt] = Query(None, description="事项ID"),
    page: int = Query(1, description="页码"),
    size: int = Query(10, description="条数"),
):
    return {"itemId": itemId, "page": page, "size": size}
0reactions
Alpha188commented, Jul 1, 2021

@dmitrijkir In some cases, it is unavoidable that the query parameters of the URL will be empty. In order to solve this problem, I can only control it on the front end. The following is the code to automatically filter the null value when sending a request using jquery

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  if (options.type && options.type.toLowerCase() == 'get') {
    var url = '';

    for (const propName of Object.keys(originalOptions.data)) {
      const value = originalOptions.data[propName];
      var part = encodeURIComponent(propName) + "=";

      if (value != null && typeof value != "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }

    url = url.slice(0, -1);
    options.data = url;
  }
});

I have not seen this situation in other technical frameworks, such as springMVC, they can help me deal with it intelligently

Read more comments on GitHub >

github_iconTop Results From Across the Web

Migration to PHP 8.1 - how to fix Deprecated Passing null to ...
In PHP 8.1 when null is passed to build in function, it is no longer silently converted to empty string.
Read more >
Using nullability in GraphQL
When you're working with a REST API, you don't always know exactly what fields you're going to get back when you call an...
Read more >
Azure Functions HTTP trigger | Microsoft Learn
The following example shows a C# function that looks for a name parameter either in the query string or the body of the...
Read more >
JavaScript Check Empty String – Checking Null or Empty in JS
Note: If the value is null, this will throw an error because the length property does not work for null. To fix this,...
Read more >
Query Parameters - Redash
If you find that you've inserted the parameter in the wrong part of the query, you can select ... Date parameters are passed...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found