I am trying to implement JWT with fastapi.
Currently looking at the following libraries
fastapi-users
FastAPI JWT Auth
In both cases, I see Depends() in method parameter.
What does Depends do when there is nothing in the parameter?
https://github.com/frankie567/fastapi-users/blob/master/fastapi_users/router/auth.py
#router.post("/login")
async def login(
response: Response, credentials: OAuth2PasswordRequestForm = Depends()
):
https://indominusbyte.github.io/fastapi-jwt-auth/usage/basic/
#app.post('/login')
def login(user: User, Authorize: AuthJWT = Depends()):
I undestand when there's a function inside the parameter but would you teach me what it does when there's no parameter with Depends?
Depends() without arguments is just a shortcut for classes as dependencies.
You see that we are having some code repetition here, writing CommonQueryParams twice:
commons: CommonQueryParams = Depends(CommonQueryParams)
FastAPI provides a shortcut for these cases, in where the dependency is specifically a class that FastAPI will "call" to create an instance of the class itself.
For those specific cases, you can do the following:
Instead of writing:
commons: CommonQueryParams = Depends(CommonQueryParams)
...you write:
commons: CommonQueryParams = Depends()
You declare the dependency as the type of the parameter, and you use Depends() as its "default" value (that after the =) for that function's parameter, without any parameter in Depends(), instead of having to write the full class again inside of Depends(CommonQueryParams).
In both cases, I see Depends() in method parameter. What does Depends do when there is nothing in the parameter?
It's a great question.
Assume you have the following code.
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional
class Location(BaseModel):
city: str
country: str
state: str
app = FastAPI()
#app.post("/withoutdepends")
async def with_depends(location: Location):
return location
#app.post("/withdepends")
async def with_depends(location: Location = Depends()):
return lcoation
We have the same Location model in two different endpoints, one uses Depends other one not.
What is the difference?
Since FastAPI is based on OpenAPI specification, we can start discovering the difference from auto-generated Swagger's docs.
This is without Depends, it expects a Request Body.
This is with Depends, it expects them as Query parameters.
How this is useful and how it works?
Actually, this is it, it expects a Callable there.
But when you use a Pydantic Model with Depends, it actually creates a query parameter for parameter inside init __init__ function.
So for example, this is the model we used above.
class Location(BaseModel):
city: str
country: str
state: str
It becomes this with Depends.
class Location(BaseModel):
def __init__(self, city: str, country: str, state: str) -> None:
...
Then they will become query parameters. This is the OpenAPI schema for the /withdepends endpoint.
"parameters": [
{
"required":true,
"schema":{
"title":"City",
"type":"string"
},
"name":"city",
"in":"query"
},
{
"required":true,
"schema":{
"title":"Country",
"type":"string"
},
"name":"country",
"in":"query"
},
{
"required":true,
"schema":{
"title":"State",
"type":"string"
},
"name":"state",
"in":"query"
}
]
This is the OpenAPI schema it created for /withoutdepends endpoint.
"requestBody": {
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/Location"
}
}
},
"required":true
}
Conclusion
Instead of request body, you can create query parameters with the same model.
Pydantic models are very useful for the cases when you have +5 parameters. But it expects a request body by default. But OpenAPI specification doesn't allow request body in GET operations. As it says in the specification.
GET, DELETE and HEAD are no longer allowed to have request body because it does not have defined semantics as per RFC 7231.
So by using Depends you are able to create query parameters for your GET endpoint, with the same model.
Related
This might seem like an odd question, or something really straightforward, but honestly I am struggling to figure out how to do this. I am working in Node.js and I want to set data I have saved on a node object into my GraphQL mutation.
I'm working with a vendor's GraqhQL API, so this isn't something I have created myself, nor do I have a schema file for it. I'm building a mutation that will insert a record into their application, and I can write out everything manually and use a tool like Postman to manually create a new record...the structure of the mutation is not my problem.
What I'm struggling to figure out is how to build the mutation with variables from my node object without just catting a bunch of strings together.
For example, this is what I'm trying to avoid:
class MyClass {
constructor() {
this.username = "my_username"
this.title = "Some Title"
}
}
const obj = new MyClass()
let query = "mutation {
createEntry( input: {
author: { username: \"" + obj.username + "\" }
title: \"" + obj.title + "\"
})
}"
I've noticed that there are a number of different node packages out there for working with Graphql, but none of their documentation that I've seen really addresses the above situation. I've been completely unsuccessful in my Googling attempts, can someone please point me in the right direction? Is there a package out there that's useful for just building queries without requiring a schema or trying to send them at the same time?
GraphQL services typically implement this spec when using HTTP as a transport. That means you can construct a POST request with four parameters:
query - A Document containing GraphQL Operations and Fragments to execute.
operationName - (Optional): The name of the Operation in the Document to execute.
variables - (Optional): Values for any Variables defined by the Operation.
extensions - (Optional): This entry is reserved for implementors to extend the protocol however they see fit.
You can use a Node-friendly version of fetch like cross-fetch, axios, request or any other library of your choice to make the actual HTTP request.
If you have dynamic values you want to substitute inside the query, you should utilize variables to do so. Variables are defined as part of your operation definition at the top of the document:
const query = `
mutation ($input: SomeInputObjectType!) {
createEntry(input: $input) {
# whatever other fields assuming the createEntry
# returns an object and not a scalar
}
}
`
Note that the type you use will depend on the type specified by the input argument -- replace SomeInputObjectType with the appropriate type name. If the vendor did not provide adequate documentation for their service, you should at least have access to a GraphiQL or GraphQL Playground instance where you can look up the argument's type. Otherwise, you can use any generic GraphQL client like Altair and view the schema that way.
Once you've constructed your query, make the request like this:
const variables = {
input: {
title: obj.title,
...
}
}
const response = await fetch(YOUR_GRAPHQL_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
})
const { data, errors } = await response.json()
I'm trying to replace our current backend service using Nestjs library,
however, I want to create a route with 2 optional parameters in the URL something like :
/route/:param1/config/:OptionalParam3?/:OptionalParam3?
that means the route should catch :
route/aa/config
route/aa/config/bb
route/aa/config/bb/cc
how can I achieve that, I have tried to use ? and () but it's not working well.
If you are looking for how to annotate an optional query parameter, you can do it like so:
#ApiQuery({
name: "myParam",
type: String,
description: "A parameter. Optional",
required: false
})
async myEndpoint(
#Query("myParam") myParam?: string
): Promise<blah> {
[...]
}
Router params name should be unique. The correct route path is:
Existing one is:
/route/:param1/config/:OptionalParam3?/:OptionalParam3?
Correction:
/route/:param1/config/:OptionalParam3?/:OptionalParam4?
Opinion: You can use query params if the params are optional. It is never a good idea to create optional param routes (disagreements agreed). Both serve the same purpose, but having them as the query params makes it more understandable for debugging and fellow developers.
I solved this problem by using #Query decorator as below:
Here is my controller:
#Get()
async getAll(#Query('someParameter') someParameter?: number) {
return this.service.getAll(someParameter);
}
Here is my client (Angular) service:
getAll(someParameter?: number) {
return this.http.get(`apiUrl/controllerAddress?someParameter=${someParameter}`
);
}
You can use this structure:
-route
-aa
-config
-[[...id]].js
It will work for the routes :
route/aa/config/{anything}
I have simple custom decorator:
export const User: () => ParameterDecorator = createParamDecorator(
(data: any, req): UserIdentity => {
const user = getUser(req);
return user;
},
);
And now, I need to validate if we have email in user object.
The problem is that I can't update my current decorator.
Could I extend my current decorator?
Create a new decorator based on the previous one or create a new decorator and combine it?
Yes, you can do "decorator composition" with Nest, but this might not be a perfect solution for your case, depending on what you intend to do when user has no email property.
As per the example from the documentation:
import { applyDecorators } from '#nestjs/common';
export function Auth(...roles: Role[]) {
return applyDecorators(
SetMetadata('roles', roles),
UseGuards(AuthGuard, RolesGuard),
ApiBearerAuth(),
ApiUnauthorizedResponse({ description: 'Unauthorized"' }),
);
}
In this example, Auth is a decorator that can be used to combine all the one passed in applyDecorators.
Thus, I'd recommend extending your decorator using a pipe.
As stated by the documentation:
Nest treats custom param decorators in the same fashion as the built-in ones (#Body(), #Param() and #Query()). This means that pipes are executed for the custom annotated parameters as well (in our examples, the user argument). Moreover, you can apply the pipe directly to the custom decorator:
#Get()
async findOne(#User(new ValidationPipe()) user: UserEntity) {
console.log(user);
}
In this example, User is a custom parameter decorator. And ValidationPipe is passed, but you can imagine passing any pipe.
Why request.url is defined as optional within nodejs types?
If a Request come to the http server should have the url by definition.
Why there is a question mark here?
url?: string;
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/http.d.ts#L288
I don't know much about http/Request in node, but this seems to be the classic example of bad modeling (which is often found in the #types/node definitions, either due to how the types have been written or to the underlying design of the node.js API itself).
IncomingMessage is being modeled as a product type with optional keys instead of as a proper sum type - to distinguish the case of a client request from a server generated one. Comments about the invariants are then put above the single fields, making them useless in terms of TS / static type checking.
Reading just that definition, a better type def could have been:
interface ClientIncomingMessage extends stream.Readable {
// ... many other fields ...
url: string;
}
interface ServerIncomingMessage extends stream.Readable {
// ... many other fields ...
// no `url` fields here!
}
type IncomingMessage = ClientIncomingMessage | ServerIncomingMessage
Modern ECMAScript-262 from 6 version supports Proxy object, which allows to intercept custom object invocations (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy )
By using Proxy-object, user can write something like obj.func1(123).func2('ABC').something, there nothing right to obj is not existing actually. Of course, by proper Proxy declaration, this chain can exist. The simplest way is return new Proxy on every property access and function invocation.
But is there way to automate this process, maybe some NPM library? The goal is transform custom free-form expression with Proxy to declarative string.
Upper example will transform to something like:
const result = obj.func1(123).func2('ABC').something;
result.__INVOCATION_VIEW__ === [
{ type: 'function', name: 'func1', args: [123] },
{ type: 'function', name: 'func2', args: ['ABC'] },
{ type: 'get', name: 'something' }
]
Pure theoretically, solution is possible anyway, because any entity in invocation chain is available as string in subsequent Proxy. But implementation is much complex. Maybe there is existing library for it?