Our customers are going to hit our new API at foo123.bar456.domain.com/v1.5/
The foo123 and bar456 subdomains are account-specific (and let us load balance). They signify relationships and trigger processing we need to do.
We don't want to (repetitively) pass query parameters in the ULR, as in ....domain.com/v1.5/?acc=foo123&parent=bar456, as that is just non-pythonic, frankly.
So, I'd like to parse, in FastAPI, the fully-qualified domain name that was called.
I can't find tips on how to do this (URL parsing) that doesn't involve folders to the right of the fqdn. Tips / pointers? Thanks!
You could call
urllib.parse.urlparse()onrequest.urlto get the hostname/domain name, and then further break it down as desired—inspired by this answer, as well as this answer and this answer.Example
Using the example below, when typing, for instance,
http://abc.def.localhost:8000/in the address bar of the browser and hitting enter, it would returnabc.def.localhost.You could also further
splitthehostname, using dot (.) as the delimiter, in order to get the subdomains. Using the URL provided earlier, the example below would return["abc","def"]. Example:Update
One does not really have to use
urllib.parse.urlparse(), in order to get thehostname. They could instead userequest.url.hostname. Hence, the updated example would look like this:Note that if the
hostname, instead ofabc.def.localhost, was, for instance,abc.def.example.com, you would then have to usesubs[:-2]in the example above, in order to exclude the top and second level domains (i.e.,comandexample) from the list of subdomains.