Skip to content

Commit

Permalink
Doc versions and response section (#2232)
Browse files Browse the repository at this point in the history
* Doc versions
  • Loading branch information
alexeyzimarev committed Jun 25, 2024
1 parent d6c4528 commit dafe8d8
Show file tree
Hide file tree
Showing 46 changed files with 5,016 additions and 759 deletions.
4 changes: 2 additions & 2 deletions docs/docs/advanced/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Constructor parameters are:
| options | Client options | Yes |
| configureDefaultHeaders | Function to configure headers. Allows to configure default headers for `HttpClient`. Most of the time you'd prefer using `client.AddDefaultHeader` instead. | No |
| configureSerialization | Function to configure client serializers with non-default options or to use a different serializer ([learn more](serialization.md)) | No |
| useClientFactory | Instructs the client to use `SimpleFactory` ([learn more](../usage/usage.md#simple-factory)) to get an `HttpClient` instance | No |
| useClientFactory | Instructs the client to use `SimpleFactory` ([learn more](../usage/client.md#simple-factory)) to get an `HttpClient` instance | No |

Here's an example of how to create a client using client options:

Expand Down Expand Up @@ -227,4 +227,4 @@ Client options apply to all requests made by the client. Sometimes, you want to
| `AdvancedResponseWriter` | Allows custom handling of the response. The function gets an instance of `HttpResponseMessage` and an instance of `RestRequest`. It must return an instance of `RestResponse`, so it effectively overrides RestSharp default functionality for creating responses. |
| `Interceptors` | Allows adding interceptors to the request. Both client-level and request-level interceptors will be called. |

The table below contains all configuration properties of `RestRequest`. To learn more about adding request parameters, check the [usage page](../usage/usage.md#create-a-request) section about creating requests with parameters.
The table below contains all configuration properties of `RestRequest`. To learn more about adding request parameters, check the [usage page](../usage/request.md) page about creating requests with parameters.
32 changes: 3 additions & 29 deletions docs/docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,11 @@
---
title: What's new
description: List of changes per RestSharp version.
description: List of changes for the current major version
sidebar_position: 2
---

# Changelog

This changelog is only maintained since v111. For release notes of previous versions, please check the [Releases page](https://github.com/restsharp/RestSharp/releases) in RestSharp GitHub repository.
For release notes of previous versions, please check the [Releases page](https://github.com/restsharp/RestSharp/releases) in RestSharp GitHub repository.

Only the most important or breaking changes are listed there. All other changes can be found in each release on GitHub.

## v111.3

New extensions:
* `RestResponse.GetHeader` for getting one response header value
* `RestResponse.GetHeaders` for getting a collection of header values
* `IRestClient.(Execute)Get(Async)` with string resource instead of request object
* `IRestClient.(Execute)Delete(Async)` with string resource instead of request object

## v111.2

* `Execute` extensions that were accidentally removed from v111 are back
* Several authenticators got renamed by unintentional refactoring, that change has also been reverted.

## v111.0

> The package for v111.0 is listed as unsupported on NuGet as it has API changes that weren't planned. Use the patched version v111.2 or later.
* Added [interceptors](advanced/interceptors.md).
* As interceptors provide a better way to interject the request and response execution flow, request properties `OnBeforeRequest`, `OnBeforeDeserialization` and `OnAfterRequest` are marked obsolete and will be removed in future versions.
* **Breaking change.** Client option `MaxTimeout` renamed to `Timeout` and changed type to `Timespan` for clarity. It doesn't configure the `HttpClient` timeout anymore. Instead, the same method is used for client and request level timeouts with cancellation tokens.
* **Breaking change.** Request option `Timeout` changed type to `Timespan` for clarity.
* Added .NET 8 target.
* Support uploading files as content without multipart form.
* Added `CacheControl` options to client and requests.
* Allow using `AddJsonBody` to serialize top-level strings.
Changes between major versions are documented in the documentation for each version on this website.
4 changes: 2 additions & 2 deletions docs/docs/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ title: Quick start
## Introduction

:::warning
RestSharp v107 changes the library API surface and its behaviour significantly. We advise looking at [v107](/v107) docs to understand how to migrate to the latest version of RestSharp.
RestSharp v107+ changes the library API surface and its behaviour significantly. We advise looking at [migration](/migration) docs to understand how to migrate to the latest version of RestSharp.
:::

The main purpose of RestSharp is to make synchronous and asynchronous calls to remote resources over HTTP. As the name suggests, the main audience of RestSharp are developers who use REST APIs. However, RestSharp can call any API over HTTP, as long as you have the resource URI and request parameters that you want to send comply with W3C HTTP standards.
Expand Down Expand Up @@ -74,7 +74,7 @@ var client = new RestClient(options);
var timeline = await client.GetJsonAsync<HomeTimeline>("statuses/home_timeline.json", cancellationToken);
```

Read [here](usage/usage.md#json-requests) about making JSON calls without preparing a request object.
Read [here](usage/execute.md#json-requests) about making JSON calls without preparing a request object.

### Content type

Expand Down
23 changes: 23 additions & 0 deletions docs/docs/usage/basics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
sidebar_position: 2
---

# RestSharp basics

This page describes some of the essential properties and features of RestSharp.

## What RestSharp does

Essentially, RestSharp is a wrapper around `HttpClient` that allows you to do the following:
- Add default parameters of any kind (not just headers) to the client, once
- Add parameters of any kind to each request (query, URL segment, form, attachment, serialized body, header) in a straightforward way
- Serialize the payload to JSON or XML if necessary
- Set the correct content headers (content type, disposition, length, etc.)
- Handle the remote endpoint response
- Deserialize the response from JSON or XML if necessary

## API client

The best way to call an external HTTP API is to create a typed client, which encapsulates RestSharp calls and doesn't expose the `RestClient` instance in public.

You can find an example of a Twitter API client on the [Example](example.md) page.
114 changes: 114 additions & 0 deletions docs/docs/usage/client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
---
sidebar_position: 3
title: Creating the client
---

## Constructors

A RestSharp client can be instantiated by one of its constructors. Two most commonly used constructors are:

#### Only specify the base URL

You can create an instance of `RestClient` with only a single parameter: the base URL. Even that isn't required as base URL can be left empty. In that case, you'd need to specify the absolute path for each call. When the base URL is set, you can use both relative and absolute path.

```csharp
// Creates a client with default options to call a given base URL
var client = new RestClient("https://localhost:5000");
```

#### Provide client options

The most common way to create a client is to use the constructor with options. The options object has the type of `RestClientOptions`.
Here's an example of how to create a client using the same base path as in the previous sample, but with a couple additional settings:

```csharp
// Creates a client using the options object
var options = new RestClientOptions("https://localhost:5000") {
MaxTimeout = 1000
};
var client = new RestClient(options);
```

#### Advanced configuration

RestSharp can be configured with more tweaks, including default request options, how it should handle responses, how serialization works, etc. You can also provide your own instance of `HttpClient` or `HttpMessageHandler`.

Read more about the advanced configuration of RestSharp on a [dedicated page](../advanced/configuration.md).

## Simple factory

Another way to create the client instance is to use a simple client factory. The factory will use the `BaseUrl` property of the client options to cache `HttpClient` instances. Every distinct base URL will get its own `HttpClient` instance. Other options don't affect the caching. Therefore, if you use different options for the same base URL, you'll get the same `HttpClient` instance, which will not be configured with the new options. Options that aren't applied _after_ the first client instance is created are:

* `Credentials`
* `UseDefaultCredentials`
* `AutomaticDecompression`
* `PreAuthenticate`
* `FollowRedirects`
* `RemoteCertificateValidationCallback`
* `ClientCertificates`
* `MaxRedirects`
* `MaxTimeout`
* `UserAgent`
* `Expect100Continue`

Constructor parameters to configure the `HttpMessageHandler` and default `HttpClient` headers configuration are also ignored for the cached instance as the factory only configures the handler once.

You need to set the `useClientFactory` parameter to `true` in the `RestClient` constructor to enable the factory.

```csharp
var client = new RestClient("https://api.twitter.com/2", true);
```

## Reusing HttpClient

RestSharp uses `HttpClient` internally to make HTTP requests. It's possible to reuse the same `HttpClient` instance for multiple `RestClient` instances. This is useful when you want to share the same connection pool between multiple `RestClient` instances.

One way of doing it is to use `RestClient` constructors that accept an instance of `HttpClient` or `HttpMessageHandler` as an argument. Note that in that case not all the options provided via `RestClientOptions` will be used. Here is the list of options that will work:

- `BaseAddress` is be used to set the base address of the `HttpClient` instance if base address is not set there already.
- `MaxTimeout` is used to cancel the call using the cancellation token source, so
- `UserAgent` will be added to the `RestClient.DefaultParameters` list as a HTTP header. This will be added to each request made by the `RestClient`, and the `HttpClient` instance will not be modified. This is to allow the `HttpClient` instance to be reused for scenarios where different `User-Agent` headers are required.
- `Expect100Continue`

Another option is to use a simple HTTP client factory as described [above](#simple-factory).

## Blazor support

Inside a Blazor webassembly app, you can make requests to external API endpoints. Microsoft examples show how to do it with `HttpClient`, and it's also possible to use RestSharp for the same purpose.

You need to remember that webassembly has some platform-specific limitations. Therefore, you won't be able to instantiate `RestClient` using all of its constructors. In fact, you can only use `RestClient` constructors that accept `HttpClient` or `HttpMessageHandler` as an argument. If you use the default parameterless constructor, it will call the option-based constructor with default options. The options-based constructor will attempt to create an `HttpMessageHandler` instance using the options provided, and it will fail with Blazor, as some of those options throw thw "Unsupported platform" exception.

Here is an example how to register the `RestClient` instance globally as a singleton:

```csharp
builder.Services.AddSingleton(new RestClient(new HttpClient()));
```

Then, on a page you can inject the instance:

```html
@page "/fetchdata"
@using RestSharp
@inject RestClient _restClient
```

And then use it:

```csharp
@code {
private WeatherForecast[]? forecasts;

protected override async Task OnInitializedAsync() {
forecasts = await _restClient.GetJsonAsync<WeatherForecast[]>("http://localhost:5104/weather");
}

public class WeatherForecast {
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}
```

In this case, the call will be made to a WebAPI server hosted at `http://localhost:5104/weather`. Remember that if the WebAPI server is not hosting the webassembly itself, it needs to have a CORS policy configured to allow the webassembly origin to access the API endpoint from the browser.
8 changes: 6 additions & 2 deletions docs/docs/usage/example.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
sidebar_position: 1
---

# Example

RestSharp works best as the foundation for a proxy class for your API. Each API would most probably require different settings for `RestClient`. Hence, a dedicated API class (and its interface) gives you sound isolation between different `RestClient` instances and make them testable.
Expand Down Expand Up @@ -46,7 +50,7 @@ public class TwitterClient : ITwitterClient, IDisposable {
}

public async Task<TwitterUser> GetUser(string user) {
var response = await _client.GetJsonAsync<TwitterSingleObject<TwitterUser>>(
var response = await _client.GetAsync<TwitterSingleObject<TwitterUser>>(
"users/by/username/{user}",
new { user }
);
Expand Down Expand Up @@ -139,7 +143,7 @@ Here we add a POST parameter `grant_type` with `client_credentials` as its value

The POST request will use the `application/x-www-form-urlencoded` content type by default.

:::note
::: note
Sample code provided on this page is a production code. For example, the authenticator might produce undesired side effect when multiple requests are made at the same time when the token hasn't been obtained yet. It can be solved rather than simply using semaphores or synchronized invocation.
:::

Expand Down
Loading

0 comments on commit dafe8d8

Please sign in to comment.