mirror of
https://github.com/FranP-code/countries.git
synced 2025-10-13 00:02:15 +00:00
ea8a14cc2856c7e8fc5a3a076ba2f6d15fdd7adf
Countries GraphQL API
A public GraphQL API for information about countries, continents, and languages. This project uses Countries List as a data source, so the schema follows the shape of that data, with a couple exceptions:
- The codes used to key the objects in the original data are available as a
codeproperty on each item returned from the API. - The
continentandlanguagesproperties are now objects and arrays of objects, respectively.
Writing queries
{
country(code: "BR") {
name
native
emoji
currency
languages {
code
name
}
}
}
{
"data": {
"country": {
"name": "Brazil",
"native": "Brasil",
"emoji": "🇧🇷",
"currency": "BRL",
"languages": [
{
"code": "pt",
"name": "Portuguese"
}
]
}
}
}
Check out the playground to explore the schema and test out some queries.
Example
A practical use of this API is to create a country select input that doesn't require you to include a large dataset of country info in your bundle.
In this example, we'll be using React and the Apollo GraphQL client. First, we'll install all of our dependencies:
$ npm install react react-dom react-apollo apollo-boost graphql graphql-tag
50.1 KB with countries-list
14.2 KB with Countries GraphQL
import React from 'react';
import ReactDOM from 'react-dom';
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'https://countries.trevorblades.com'
});
const GET_COUNTRIES = gql`
{
countries {
name
code
}
}
`;
class App extends Component {
state = {
country: ''
};
onCountryChange = event =>
this.setState({country: event.target.value});
render() {
return (
<ApolloProvider client={client}>
<Query query={GET_COUNTRIES}>
{({loading, error, data}) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<select
value={this.state.country}
onChange={this.onCountryChange}
>
{data.countries.map(country => (
<option key={country.code} value={country.code}>
{country.name}
</option>
))}
</select>
);
}}
</Query>
</ApolloProvider>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Languages
JavaScript
99.6%
Procfile
0.4%