@mahdi.golzar/apiclient
v1.0.0
Published
APIClient is a versatile HTTP client designed to interact with various APIs, including REST and GraphQL. It provides a simple interface for making API requests and handling responses.
Downloads
2
Readme
APIClient
APIClient is a versatile HTTP client designed to interact with various APIs, including REST and GraphQL. It provides a simple interface for making API requests and handling responses.
Features
- REST API Support: GET, POST, PUT, DELETE requests.
- GraphQL API Support: Query and mutation execution.
- Custom Headers: Easily set and modify request headers.
- Query Parameters: Automatically build URLs with query parameters.
Installation
No installation is required for this code as it is self-contained and can be added directly to your project.
Usage
- Create an APIClient Instance
baseURL: The base URL of the API. headers: Optional default headers to be included with every request.const apiClient = new APIClient('https://api.example.com/', { 'Authorization': 'Bearer YOUR_TOKEN_HERE', });
- Sending Requests
REST API Example
GET Request with Parameters
POST RequestapiClient.get('/users', { limit: 10 }).then(users => { console.log('Fetched users:', users); });
PUT RequestapiClient.post('/users', { name: 'John Doe', email: '[email protected]' }).then(newUser => { console.log('Created user:', newUser); });
DELETE RequestapiClient.put('/users/1', { name: 'John Smith' }).then(updatedUser => { console.log('Updated user:', updatedUser); });
GraphQL API ExampleapiClient.delete('/users/1').then(response => { console.log('Deleted user:', response); });
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
const variables = { id: 1 };
apiClient.graphql(query, variables).then(response => {
console.log('GraphQL response:', response);
});