async-graphql/docs/en/src/quickstart.md

64 lines
1.8 KiB
Markdown
Raw Normal View History

2020-04-15 03:15:30 +00:00
# Quickstart
2020-04-22 03:16:41 +00:00
## Add dependency libraries
```toml
[dependencies]
2022-05-27 07:20:58 +00:00
async-graphql = "4.0"
async-graphql-actix-web = "4.0" # If you need to integrate into actix-web
async-graphql-warp = "4.0" # If you need to integrate into warp
async-graphql-tide = "4.0" # If you need to integrate into tide
2020-04-22 03:16:41 +00:00
```
## Write a Schema
2020-09-28 09:44:00 +00:00
The Schema of a GraphQL contains a required Query, an optional Mutation, and an optional Subscription. These object types are described using the structure of the Rust language. The field of the structure corresponds to the field of the GraphQL object.
2020-04-22 03:16:41 +00:00
`Async-graphql` implements the mapping of common data types to GraphQL types, such as `i32`, `f64`, `Option<T>`, `Vec<T>`, etc. Also, you can [extend these base types](custom_scalars.md), which are called scalars in the GraphQL.
Here is a simple example where we provide just one query that returns the sum of `a` and `b`.
```rust
# extern crate async_graphql;
2020-04-22 03:16:41 +00:00
use async_graphql::*;
struct Query;
#[Object]
2020-04-22 03:16:41 +00:00
impl Query {
2020-09-28 06:43:12 +00:00
/// Returns the sum of a and b
async fn add(&self, a: i32, b: i32) -> i32 {
2020-04-22 03:16:41 +00:00
a + b
}
}
```
## Execute the query
2020-09-01 05:47:22 +00:00
In our example, there is only a Query without a Mutation or Subscription, so we create the Schema with `EmptyMutation` and `EmptySubscription`, and then call `Schema::execute` to execute the Query.
2020-04-22 03:16:41 +00:00
```rust
# extern crate async_graphql;
# use async_graphql::*;
#
# struct Query;
# #[Object]
# impl Query {
# async fn version(&self) -> &str { "1.0" }
# }
# async fn other() {
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
2020-09-17 00:14:07 +00:00
let res = schema.execute("{ add(a: 10, b: 20) }").await;
# }
2020-04-22 03:16:41 +00:00
```
## Output the query results as JSON
```rust,ignore
2020-09-17 00:14:07 +00:00
let json = serde_json::to_string(&res);
2020-04-22 03:16:41 +00:00
```
## Web server integration
2020-09-01 05:47:22 +00:00
Please refer to <https://github.com/async-graphql/examples>.