website/src/docs/hotchocolate/v14/defining-a-schema/arguments.md
GraphQL allows us to specify arguments on a field and access their values in the field's resolver.
type Query {
user(id: ID!): User
}
Clients can specify arguments like the following.
{
user(id: "123") {
username
}
}
Often times arguments will be specified using variables.
query ($userId: ID!) {
user(id: $userId) {
username
}
}
Learn more about arguments here and variables here.
Arguments can be defined like the following.
<ExampleTabs> <Implementation>public class Query
{
public User GetUser(string username)
{
// Omitted code for brevity
}
}
We can also change the name of the argument used in the schema.
public class Query
{
public User GetUser([GraphQLName("name")] string username)
{
// Omitted code for brevity
}
}
public class QueryType : ObjectType
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Name(OperationTypeNames.Query);
descriptor
.Field("user")
.Argument("username", a => a.Type<NonNullType<StringType>>())
.Resolve(context =>
{
var username = context.ArgumentValue<string>("username");
// Omitted code for brevity
});
}
}
We can also access nullable values through an Optional<T>.
var username = context.ArgumentOptional<string>("username");
if (username.HasValue)
{
// use username.Value
}
builder.Services
.AddGraphQLServer()
.AddDocumentFromString(@"
type Query {
user(username: String!): User
}
")
.AddResolver("Query", "user", (context) =>
{
var username = context.ArgumentValue<string>("username");
// Omitted code for brevity
});
Arguments can be made required by using the non-null type. Learn more about non-null
If we need to provide complex objects as arguments, we can use input object types.